PHP's assignment by reference is not working as expected

后端 未结 7 1551
迷失自我
迷失自我 2021-01-29 08:04

Why the following

class AClass
{
    public function __construct ()
    {
        $this->prop = \"Hello\";
    }
    public function &get ()
    {
                


        
7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-29 08:33

    Consider this piece of code (It's the same as your code, just without everything else):

    $value = new stdClass;
    $ref = &$value;
    $var = "Hello";
    $ref = &$var; // this is where you write $ref = &$ref->get();
    var_dump($value);
    

    This gives as expected an empty object and not string(5) Hello.

    Why?

    We're in line 4 overwriting the reference to $value with a reference to $var.

    $ref now holds a reference to $var; the value of $value remains unaffected.

    What we're not doing

    • We don't assign the value of $var to $value.
    • We don't assign to $value a reference to $var.

    Conclusion

    Assigning references to a variable via another referencing variable is just not possible in PHP.

提交回复
热议问题