Are PHP5 objects passed by reference?

后端 未结 8 805
抹茶落季
抹茶落季 2020-11-27 03:45

I can\'t seem to get any consistent info on this. Different sources appear to say different things and the venerable php.net itself (appears) not to explicitly stat

8条回答
  •  天命终不由人
    2020-11-27 04:28

    Just an example where passing "objects" by reference is useful:

    class RefTest1
    {
        public $foo;
    
        public function __construct(RefTest2 &$ref = null)
        {
            $this->foo =& $ref;
        }
    }
    
    class RefTest2
    {
        public $foo;
    
        public function __construct(RefTest1 &$ref = null)
        {
            $this->foo =& $ref;
        }
    }
    
    class RefTest3
    {
        public $foo;
    
        public function __construct(RefTest2 &$ref = null)
        {
            $this->foo =& $ref;
        }
    }
    
    class DoCrossRef
    {
        public $refTest1;
        public $refTest2;
    
        public function __construct()
        {
            $this->refTest1 = new RefTest1($this->refTest2);
            $this->refTest2 = new RefTest2($this->refTest1);
        }
    
        public function changeReference()
        {
            $this->refTest1 = new RefTest3($this->refTest2);
        }
    }
    

    At the end RefTest1 holds a reference to RefTest2 and the other way around, also if the RefTest2 object did not exist at the time RefTest1 was created.

    After calling DoCrossRef->changeReference(), the RefTest2 objects also holds a reference to the new RefTest3 object.

提交回复
热议问题