PHP's assignment by reference is not working as expected

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

Why the following

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


        
7条回答
  •  礼貌的吻别
    2021-01-29 08:40

    Just change protected into public for the sake of testing.

    $value = new AClass();
    $myValue = &$value->get();
    
    var_dump($myValue );
    var_dump($value->prop);
    $value->prop = 'test';
    var_dump($value->prop);
    var_dump($myValue );
    

    Output :

     string 'Hello' (length=5)
     string 'Hello' (length=5)
     string 'test' (length=4)
     string 'test' (length=4)
    

    incase you think that function is necessary you can use global variable.

提交回复
热议问题