开发者

PHP reference pass makes new instance of an object?

I have a ParentClass and when I make a new object I want to pass a reference to the ParentClass. (I have to use the ParentClass things in the new object)

I use the constructor to make this object and pass the reference value. (that's important for me)

But when I use the =& operator, it makes a new instance of the ParentClass, what call the constructor, and then it's fall an endless recursion.

Here's my code:

<?php

abstract class MainClass {

    function __construct(&$parent){
        $this->parent =& $parent;
        $this->init();
    }

    abstract protected function init(); 

}

class ParentClass extends MainClass {   

    protected function init(){
        $th开发者_开发百科is->child = new ChildClass($this);
    }

}

class ChildClass extends MainClass {

    protected function init(){}

}


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

?>

And the result:

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*
       }
     }
   }
 }

How can I solve this problem?


Objects are passed by reference by default. There is no reason to pass or assign the $parent by reference. So this should be sufficient:

abstract class MainClass {

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

It might be important to you to use &$parent, but it is totally unnecessary.


Regarding the recursion: There is no recursion in your code, it is recursion in the output.

This part:

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*
      }
    }
  }

would be printed over and over again, because the child has a reference to its parent and the parent a reference to its child.

Maybe even more obvious are the repeating numbers in the output:

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

This is normal, there is no problem.


Better design.

You shouldn't need a reference to the parent class. If there are methods that need something like that, then they should be static methods that cover all child objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜