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--) {
       ...
   }
}

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

Comments are closed.

Scroll to Top