&安培;在PHP中并不意味着地址?那么如何在树节点中存储父指针?

时间:2009-08-21 07:03:45

标签: php tree

当我将一个节点添加到树中时,我将其父地址(我想是这样)存储在其中:

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

但是当我尝试回显$ child-> ref_parent 时,它失败了“可捕获的致命错误:类节点的对象无法转换为字符串...”,我使用&我不想在它的孩子中存储父对象,但似乎不起作用,任何想法?

3 个答案:

答案 0 :(得分:9)

由于您收到的错误消息是“可捕获致命错误”,因此表明您使用的是PHP5,而不是PHP4。从PHP5开始,对象总是通过引用传递,因此您不需要使用'&'。

顺便问一下:你的问题是什么?它似乎工作正常,你得到的错误是由于你的类无法转换为字符串,所以你不能将它与echo一起使用。尝试实施神奇的__toString()方法,以便在echo时显示有用的内容。

答案 1 :(得分:5)

不,不,不。你不能分解为像PHP中的内存地址这样的低级概念。您无法获取值的内存地址。 $this和其他对象始终通过引用传递,因此不会复制该对象。至少在PHP5中。

答案 2 :(得分:4)

无论如何,php5对象都是通过引用传递的,所以你不需要&amp ;.无论是在方法的声明中还是在方法调用中(也不推荐使用)。

<?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;
  }
}

打印

2, 1
2, 0

这意味着$ child确实存储了与$ parent相同的对象的引用(不是副本或写入时复制)。