PHP引用过程生成对象的新实例


PHP reference pass makes new instance of an object?

我有一个ParentClass,当我创建一个新对象时,我想传递对ParentClass的引用。(我必须在新对象中使用ParentClass内容)

我使用构造函数来创建这个对象并传递引用值。(这对我很重要)

但当我使用=&运算符时,它会生成ParentClass的一个新实例,即构造函数,然后它就变成了一个无休止的递归。

这是我的代码:

<?php
abstract class MainClass {
    function __construct(&$parent){
        $this->parent =& $parent;
        $this->init();
    }
    abstract protected function init(); 
}
class ParentClass extends MainClass {   
    protected function init(){
        $this->child = new ChildClass($this);
    }
}
class ChildClass extends MainClass {
    protected function init(){}
}

$parent = new ParentClass (new stdClass());
var_dump($parent);
?>

结果:

object(ParentClass)#1 (2) {
  ["parent"]=>
   object(stdClass)#2 (0) {
  }
  ["child"]=>
   object(ChildClass)#3 (1) {
     ["parent"]=>
     object(ParentClass)#1 (2) {
       ["parent"]=>
       object(stdClass)#2 (0) {
       }
       ["child"]=>
       object(ChildClass)#3 (1) {
         ["parent"]=>
         *RECURSION*
       }
     }
   }
 }

我该如何解决这个问题?

默认情况下,通过引用传递对象。没有理由通过引用传递或分配$parent。所以这就足够了:

abstract class MainClass {
    function __construct($parent){
        $this->parent = $parent;
        $this->init();
    }

使用&$parent对您来说可能很重要,但完全没有必要。


关于递归:您的代码中没有递归,它是输出中的递归。

本部分:

object(ChildClass)#3 (1) {                // <--- the same element
    ["parent"]=>
    object(ParentClass)#1 (2) {
      ["parent"]=>
      object(stdClass)#2 (0) {
      }
      ["child"]=> 
      object(ChildClass)#3 (1) {          // <--- the same element
        ["parent"]=>
        *RECURSION*
      }
    }
  }

将被一遍又一遍地打印,因为子对象有对其父对象的引用,而父对象有对其子对象的引用。

也许更明显的是输出中的重复数字:

object(ParentClass)#1            // 1
  object(stdClass)#2             // 2
  object(ChildClass)#3           // 3
    object(ParentClass)#1        // 1
      object(stdClass)#2         // 2
      object(ChildClass)#3       // 3
        // what would be here? right, object(ParentClass)#1 again

这很正常,没有问题。

更好的设计。

您不应该需要对父类的引用。如果有一些方法需要这样的东西,那么它们应该是覆盖所有子对象的静态方法。