If you like SEOmastering Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

Global scope

Started by beingchinmay, 11-26-2016, 04: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;



If you like SEOmastering Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...