繁体   English   中英

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

这很正常,没有问题。

更好的设计。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM