Book HomePHP CookbookSearch this book

6.12. Accessing a Global Variable Inside a Function

6.12.2. Solution

Bring the global variable into local scope with the global keyword:

function eat_fruit($fruit) {
   global $chew_count;
 
   for ($i = $chew_count; $i > 0; $i--) {
       ...
   }
}

Or reference it directly in $GLOBALS:

function eat_fruit($fruit) {
   for ($i = $GLOBALS['chew_count']; $i > 0; $i--) {
       ...
   }
}


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.