Global scope

Started by beingchinmay, 11-26-2016, 02:33:42

Previous topic - Next topic

beingchinmayTopic starter

Variables declared outside a function are global. That is, they can be accessed from any part of the program. However, by default, they are not available inside functions. To allow a function to access a global variable, you can use the global keyword inside the function to declare the variable within the function. Here's how we can rewrite the update_counter( ) function to allow it to access the global $counter variable:


function update_counter ( ) {
global $counter;
$counter++;
}
$counter = 10;
update_counter( );
echo $counter;
11


A more cumbersome way to update the global variable is to use PHP's $GLOBALS array instead of accessing the variable directly:

function update_counter ( ) {
$GLOBALS[counter]++;
}
$counter = 10;
update_counter( );
echo $counter;