我试图理解 PHP 引用,但在使用链接引用时发现了一个问题。
class A
{
public $val;
public function __construct($val)
{
$this->val = $val;
}
}
$values = array(
'a' => new A('a'),
'b' => new A('b'),
'c' => new A('c')
);
$values['a'] = &$values['b'];
$values['b'] = &$values['c'];
返回:
array(
'a' => new A('b'),
'b' => new A('c'),
'c' => new A('c')
)
为什么对象 A 中键“a”的“val”是“b”?我预计该值为“c”。谢谢
最佳答案
尽量避免引用,它们可能会给您带来难以调试的麻烦。此外,对象在幕后被引用;这意味着:
$a1 = new A('a');
$a2 = $a1;
类似于:
$b1 = new A('a');
$b2 = &$b1;
顺便说一句:
$a2->val = 1; // $a1->val is now equal to 1, because $a1 and $a2 are pointing
// to the same instance
$b2->val = 1; // $b1->val is now equal to 1, because $b2 points to $b1
但是有一个微妙的区别:
$a1 = 1; // $a2 still points to A object
$b1 = 1; // $b2 still points to $a1 which points to number 1,
// therefore $b2 == 1
此外,它与数组的工作方式略有不同,因为数组赋值总是涉及值复制。
如果您想了解示例中发生的情况,让我们看一下:
所以你的原始数组是这样的:
$values = array(
'a' => new A('a'),
'b' => new A('b'),
'c' => new A('c')
);
让我们一步步看看里面发生了什么:
$values['a'] = &$values['b']; // $values['a'] is now reference to new A('b')
// that means your original new A('a') is now
// lost
$values['b'] = &$values['c']; // $values['b'] is now reference to new A('c')
// stored under 'c' key, that means $values['b']
// is now equal to $values['c'] ; note that this is
// different than $b2 = &$b1; from the above example
// since we use an array and not bare variables
// the $values['a'] points to value stored under
// the 'b' key, but we replace the 'b' key value
// as opposed to giving it a new value;
// "Array assignment always involves value copying."
// So you ended up with this result:
array(
'a' => new A('b'),
'b' => new A('c'), // this is actually reference to 'c', just wrote new A()
// to keep this part consistent with your question's
// formatting
'c' => new A('c')
)
关于php - PHP 中的链接引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19067482/