phpglobal-variablesstatic-variables

Do static and global modifiers for variables implement a non-modifiable reference?


Source

The PHP doc says

PHP implements the static and global modifier for variables in terms of references.

<?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);
?>

Since the program yields NULL as the first output, is this to say that the implemented reference is non-modifiable(hence the reference to &$new is nullified somehow)? The doc says the implementation results in an unexpected behaviour. Is there a logical explanation to this?


Solution

  • This is not about global or static, this is about the concept of reference.

    Think about the following codes:

    $a = "a"; $b = "b";
    
    $r = &$a;
    var_dump($a, $b, $r); # a, b, a
    
    $r = &$b;
    var_dump($a, $b, $r); # a, b, b
    

    It's easy to understand, but the important thing is the statement $r = &$b; means copy the reference of $b to $r, so both $b and $r refer to the same value.

    Next if you do:

    $r = $a;
    var_dump($a, $b, $r); # a, a, a
    

    The statement $r = $a; means copy the value of $a to $r, so the value of $r changes from "b" to "a". Since both $b and $r refer to the same value, the value of $b also becomes "a".

    Finally if you do:

    $r = "r";
    var_dump($a, $b, $r); # a, r, r
    

    Still only the value of $b to $r is changed, $a keeps its original value.


    Back to your question, your first function is almost equivalent to:

    function test_global_ref(&$r) {
        $b = "b";
        $r = &$b;
    }
    
    $a = "a";
    test_global_ref($a);
    

    I changed the variable names and values to those corresponding to the above example, hope this is easier to understand. So the global variable $a is passed to the function as a reference $r, when you copy the reference of $b to $r, the global variable $a won't be influenced.