【问题标题】:& in PHP doesn't mean address? then how to store parent pointer in a tree-node?& 在 PHP 中并不意味着地址?那么如何将父指针存储在树节点中?
【发布时间】:2009-08-21 07:03:45
【问题描述】:

当我向树中添加一个节点时,我会在其中存储它的父地址(我是这么认为的):

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

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

【问题讨论】:

  • 需要更多的支持。我们都犯的范式转换错误的完美例子。
  • @e-satis:我不同意。实际上,这个问题是由于没有阅读手册并做出一些奇怪的假设 PHP 就像 C像 C++ 中的操作符,$this 也必须是一个指针。因此,&$this 将是 object** 类型。所以,我当然不会投票,因为我认为这不是一个特别好的问题。

标签: php tree


【解决方案1】:

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

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

【讨论】:

  • 是的,我使用 echo 只是想确保它是一个地址(以 C 方式思考),现在我了解到父数据不是以这种方式复制的,感谢您的描述
【解决方案2】:

不,不,不。您不能分解为 PHP 中的内存地址等低级概念。您无法获得值的内存地址。 $this 和其他对象总是通过引用传递,因此对象不会被复制。至少在 PHP5 中。

【讨论】:

    【解决方案3】:

    php5 对象是通过引用传递的,所以你不需要 &。既不在方法的声明中,也不在方法调用中(也不推荐使用)。

    <?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 相同的对象的引用(不是副本或写时复制)。

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 2018-05-12
      • 2021-07-02
      • 2016-10-02
      • 2014-10-25
      • 2017-11-08
      相关资源
      最近更新 更多