Home > Net >  Can I pass a PHP object to a constructor for that same object?
Can I pass a PHP object to a constructor for that same object?

Time:02-15

(SO closed out my previous question, so I will try to be clearer this time) When I run the following code in my browser:

<?php
class MyNode {
    public $name;
    public $children = array();
    public $parent;

    public function __construct(string $name, $parent) {
        echo "in constructor\n";
      $this->name = $name;
      echo "name: " . $this->name . ".\n";
      $this->parent = $parent;
      #$this->parent = &$parent;
      echo "parent: " . $this->parent . ".\n";
    }
}
$RootNode = new MyNode("Root", null);
echo "done root x\n";
#$ChildNode = new MyNode("Child1", null);
$ChildNode = new MyNode("Child1", $RootNode);
echo "done child\n";
?>

The browser prints "in constructor name: Root. parent: . done root x in constructor name: Child1." and then stops with the error (in Developer console) "500 (Internal Server Error)". If I use the line (commented above) that passes null instead of $RootNode, it succeeds.

What is the right way to pass $RootNode to the MyNode constructor?

CodePudding user response:

You're extremely close - if you had error reporting on, the issue would be fairly clear. Your code is emitting an error when it tries to print $this->parent because PHP can't convert instances of MyNode to a string - which PHP needs to do to print it.

Here's an example of your code. It's emitting this error:

Fatal error: Uncaught Error: Object of class MyNode could not be converted to string in /in/T7Os5:12
Stack trace:
#0 /in/T7Os5(18): MyNode->__construct('Child1', Object(MyNode))
#1 {main}
  thrown in /in/T7Os5 on line 12

I suggest implementing a __toString() method (example):

<?php
class MyNode {
    public $name;
    public $children = array();
    public $parent;

    public function __construct(string $name, $parent) {
      echo "in constructor\n";
      $this->name = $name;
      echo "name: " . $this->name . ".\n";
      $this->parent = $parent;
      echo "parent: " . $this->parent . ".\n";
    }
    
    public function __toString()
    {
        return $this->name;
    }
}

$RootNode = new MyNode("Root", null);
echo "done root x\n";
$ChildNode = new MyNode("Child1", $RootNode);
echo "done child\n";
  • Related