PHP's assignment by reference is not working as expected

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

Why the following

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


        
7条回答
  •  迷失自我
    2021-01-29 08:15

    class AClass
    {
        public function __construct ()
        {
            $this->prop = "Hello";
        }
        public function &get ()
        {
            return $this->prop;
        }
        protected $prop;
    }
    
    function func (&$ref)
    {
        $ref = $ref->get(); // You don't need the ampersand here
    }
    
    $value = new AClass();
    func($value);
    var_dump( $value ); // outputs: string(5) "Hello"
    

提交回复
热议问题