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?
This is not about global or static, this is about the concept of reference.
Think about the following codes:
It's easy to understand, but the important thing is the statement
$r = &$b;means copy the reference of$bto$r, so both$band$rrefer to the same value.Next if you do:
The statement
$r = $a;means copy the value of$ato$r, so the value of$rchanges from "b" to "a". Since both$band$rrefer to the same value, the value of$balso becomes "a".Finally if you do:
Still only the value of
$bto$ris changed,$akeeps its original value.Back to your question, your first function is almost equivalent to:
I changed the variable names and values to those corresponding to the above example, hope this is easier to understand. So the global variable
$ais passed to the function as a reference$r, when you copy the reference of$bto$r, the global variable$awon't be influenced.