在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
)的引用。如果我不使用运算符,它的行为很奇怪。它正在调用游标类的构造函数。显然,这不仅仅是复制参考。我认为,从$object1 = $object2
上的PHP5和$object1 = & $object2
相同,它与其他类型(字符串等)不同。我觉得我的假设是错误的。
答案 0 :(得分:0)
这里详细解释:http://php.net/manual/en/language.oop5.references.php
通过"默认" 或"引用" 传递对象有所不同。 默认情况下,通过复制对象的标识符来传递对象。
我认为以下代码(上页)明确说明:
<?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
(如果你问我,这是相当丑陋的,但事实就是如此;))。