tags:

views:

160

answers:

3

When i add a node to a tree, i store its parent address (i thought so) 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 on "Catchable fatal error: Object of class Node could not be converted to string...", i use & cos i don't want to store parent object in its child, but seems don't work, any idea?

+5  A: 

No, no, no. You can't break down to such low level concepts like memory addresses in PHP. You can't get a memory address of a value. $this and other objects are always passed by reference, so the object doesn't get copied. At least in PHP5.

Ignas R
+8  A: 

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

By the way: What is your problem? It seems to work all right, the error you are getting is caused by the fact that your class cannot be converted to string, so you cannot use it with echo. Try to implement the magic __toString() method in order to display something useful when echo-ing it.

Ferdinand Beyer
Yep, i use echo just want to make sure it is an address (thought in C ways), now i learned parent data are not copied in this way, thanks for description
Edward
+4  A: 

With php5 objects are passed by reference anyway, so you don't need the &. Neither in the method's declaration nor in the method call (which also is 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 really stores a reference to the same object as $parent does (not a copy or a copy-on-write-thingeling).

VolkerK