对象未作为引用


Object not behaving as reference

在PHP中,我假设每个对象都是引用,但在这段代码中;

  /**
 * adds a master object which affects browse and insert operations
 *
 * @param 'bk'dataset'master|string $cursor            
 * @param Array $fields            
 */
function SetMasterCursor ($cursor, $fields)
{
    if (is_object($cursor)) {
        $this->master = & $cursor; /** !!!!!! **/
    } elseif (is_string($cursor)) {
        $this->master = 'bk'dataset'master::instance($cursor, null, $this->GetModuleName());
    }
    $this->_masterfld = $fields;
}

我需要强制PHP使用带有&运算符($this->master = & $cursor)的引用。如果我不使用运算符,它的行为会很奇怪。它正在调用游标类的构造函数。很明显,这不仅仅是复制参考文献。我想,从PHP5到$object1 = $object2$object1 = & $object2是一样的,只是其他类型(字符串等)不同。我觉得我的假设是错误的。

这里将对此进行详细解释:http://php.net/manual/en/language.oop5.references.php

通过"default"或通过<reference">

我认为(上一页的)以下代码表明了这一点:

<?php
class Foo {
  private static $used;
  private $id;
  public function __construct() {
    $this->id = self::$used++;
  }
  public function __clone() {
    $this->id = self::$used++;
  }
}
$a = new Foo; // $a is a pointer pointing to Foo object 0
$b = $a; // $b is a pointer pointing to Foo object 0, however, $b is a copy of $a
$c = &$a; // $c and $a are now references of a pointer pointing to Foo object 0
$a = new Foo; // $a and $c are now references of a pointer pointing to Foo object 1, $b is still a pointer pointing to Foo object 0

(如果你问我的话,这很难看,但事实就是这样;))。