'Can I pass a PHP object to a constructor for that same object?

(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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source