Categories
PHP Tips & Tutorials

PHP: How to access a global variable inside a function without passing it?

Ideally, global variables outside a function can not and should not be accessed from within the function to hold up the programming modularization paradigm.

However, if you really need to do this, especially in small programs, you can declare the variable again inside the function by the keyword ‘global’ so as to use inside the local scope it by reference without passing the variable as an argument.

function eat_fruit($fruit) {
   global $chew_count;

   for ($i = $chew_count; $i > 0; $i--) {
       ...
   }
}

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.

One reply on “PHP: How to access a global variable inside a function without passing it?”

Comments are closed.