PHP's assignment by reference is not working as expected

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

Why the following

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


        
7条回答
  •  离开以前
    2021-01-29 08:32

    bwoebi is totally right about how PHP references work. Without a dereference operator it would become impossible to know exactly what you mean when using pointers, so PHP has used another approach. This does not, however, mean that what you want is impossible, you just can't do it all inside a function:

    class AClass
    {
        public function __construct ()
        {
            $this->prop = "Hello";
        }
        public function &get()
        {
            return $this->prop;
        }
        public $prop;
    }
    
    function &func($ref)
    {
        return $ref->get();
    }
    
    $root = new AClass();
    $value = &func( $root );
    var_dump( $value );
      // string(5) "Hello"
    $value = "World";
    var_dump( $root->get() );
      // string(5) "World"
    

    http://codepad.org/gU6pfzUO

提交回复
热议问题