What exactly global keyword does in PHP
<?php
$x = 1; // here I defined global variable x, now $_GLOBALS['x' => 1]
function my_function()
{
echo $x; // outputs a notice that says 'Undefined variable: x', because php functions don't access global variables directly, but through reference
$x = 2; // here I defined local variable x
echo $x; // outputs 2
global $x; // Now the local variable x has got the reference of the global variable x that means 'globals $x' statement equals to $x = &$_GLOBALS['x']. If there was no global variable named x then a global variable named x would be created containing null as its value and the local variable x would have its reference as value.
echo $x; // outputs 1
}
my_function();
?>
$x = 1; // here I defined global variable x, now $_GLOBALS['x' => 1]
function my_function()
{
echo $x; // outputs a notice that says 'Undefined variable: x', because php functions don't access global variables directly, but through reference
$x = 2; // here I defined local variable x
echo $x; // outputs 2
global $x; // Now the local variable x has got the reference of the global variable x that means 'globals $x' statement equals to $x = &$_GLOBALS['x']. If there was no global variable named x then a global variable named x would be created containing null as its value and the local variable x would have its reference as value.
echo $x; // outputs 1
}
my_function();
?>
Comments
Post a Comment