& in PHP does not mean address? then how to store the parent pointer in the tree node?

When I add a node to the tree, I store its parent address (I thought) in it:

-- Client --
$parent = new Node();
$child = new Node();
$parent->add($child)

-- Class Node --
function add($child) {
    $this->setParent(&$this);
    $this->children[] = $child;
}

function setParent($ref_parent) {
    $this->ref_parent = $ref_parent;
}

      

But when I try to echo $ child-> ref_parent it fails regarding "Catchable fatal error: Object of class node cannot be converted to string ...", I use and Because I do not want to store parent object in my child but doesn't seem to work, any idea?

+2


source to share


3 answers


No no no. You cannot break down low level concepts like memory addresses in PHP. You cannot get the memory address of the value. $this

and other objects are always passed by reference, so the object is not copied. At least in PHP5.



+5


source


Since the error message you receive is a "catchable fatal error", it indicates that you are using PHP5 and not PHP4. Since PHP5, objects are always passed by reference, so you don't need to use "&".



By the way: What's your problem? Everything seems to be in order, the error you are getting is because your class cannot be converted to a string, so you cannot echo it. Try to implement a magic method __toString()

to display something useful when echo

-ing.

+9


source


Php5 objects are passed by reference anyway, so you don't need &. Neither in the method declaration nor in the method call (which is also deprecated).

<?php
$parent = new Node();
$child = new Node();
$parent->add($child);
$child->foo(); echo "\n";
// decrease the id of $parent
$parent->bar();
// and check whether $child (still) references
// the same object as $parent
$child->foo(); echo "\n";

class Node {
  private $ref_parent = null;
  private $id;

  public function __construct() {
    static $counter = 0;
    $this->id = ++$counter;
  }  

  function add($child) {
    $child->setParent($this);
    $this->children[] = $child;
  }

  function setParent($ref_parent) {
    $this->ref_parent = $ref_parent;
  }

  public function foo() {
    echo $this->id;
    if ( !is_null($this->ref_parent) ) {
      echo ', ';
      $this->ref_parent->foo();
    }
  }

  public function bar() {
    $this->id -= 1;
  }
}

      

prints

2, 1
2, 0

      

which means that $ child does indeed store a reference to the same object as $ parent (not copy or copy to write).

+4


source







All Articles