Why do different delivery methods have different results when applying PHP's global keyword?

49 Views Asked by At

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?

1

There are 1 best solutions below

0
ceejayoz On

In the first code sample, $obj is set as a reference to $new. When that function ends, $new is cleaned up (as it's no longer in scope for any actively running code), leaving the reference going nowhere.

In the second sample, $obj is set to $new without using a reference, so PHP knows to keep the value around.