Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

6.11. Accessing a Global Variable Inside a Function

Problem

You need to access a global variable inside a function.

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

Discussion

If you use a number of global variables inside a function, the global keyword may make the syntax of the function easier to understand, especially if the global variables are interpolated in strings.

You can use the global keyword to bring multiple global variables into local scope by specifying the variables as a comma-separated list:

global $age,$gender,shoe_size;

You can also specify the names of global variables using variable variables:

$which_var = 'age';
global $$which_var; // refers to the global variable $age

However, if you call unset( ) on a variable brought into local scope using the global keyword, the variable is unset only within the function. To unset the variable in the global scope, you must call unset( ) on the element of the $GLOBALS array:

$food =  'pizza';
$drink = 'beer';

function party( ) {
    global $food, $drink;
    
    unset($food);             // eat pizza
    unset($GLOBALS['drink']); // drink beer
}

print "$food: $drink\n";
party( );
print "$food: $drink\n";
pizza: beer
               pizza:

You can see that $food stayed the same, while $drink was unset. Declaring a variable global ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata