0

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?

2
  • 1
    a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable Looking at this, I simply feel the first one said NULL because it was pointing to the address of a local variable which got garbage collected when the function call finished. See onecompiler.com/php/3yxabtfmm Commented Feb 8, 2023 at 8:36
  • 1
    @nice_dev Interesting thought. Commented Feb 8, 2023 at 8:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So, changing the reference simply overrides the existing reference without affecting the initial reference?
Yes, each variable has its own reference, changing one's doesn't affect other's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.