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

by Yang Yang on April 22, 2009

Share This Article:
Subscribe to Kavoir: blog feed

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--) {
       ...
   }
}
Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 1 comment… read it below or add one }

shaffy August 2, 2010 at 1:46 pm

good done

Reply

Leave a Comment

Previous post:

Next post: