PHP implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
<?php function test_global_ref() { global $obj; $new = new stdClass; $obj =& $new; } function test_global_noref() { global $obj; $new = new stdClass; $obj = $new; } test_global_ref(); var_dump($obj); test_global_noref(); var_dump($obj); ?>The above example will output:
NULL object(stdClass)#1 (0) { }
URL: https://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.references
I found this example on the variable scope page of the PHP manual, but I don't understand why the first var_dump is null. I even output $obj in the test_global_ref function. $obj still has value, but why is it null when outputting $obj in the global scope?
In the first code sample,
$objis set as a reference to$new. When that function ends,$newis cleaned up (as it's no longer in scope for any actively running code), leaving the reference going nowhere.In the second sample,
$objis set to$newwithout using a reference, so PHP knows to keep the value around.