请帮助我了解此症状是否是 PHP 中的意外错误/不良优化/或预期行为。
这是一个小代码:
class Packet {
public $length;
public $time;
}
class Stream {
public $packets = array();
// Basically what I want is to make sure
// I put my packet in the array as reference
// because later in the code where I call this
// function, I change my Packet object's values
// and I want this change to appear in the
// $this->packets array. So I pass by reference.
// I don't want to copy the Packet object at all!
public function addPacket(&$packet){
$this->packets[] = &$packet; //note here the reference operator
}
}
...
foreach($packets as $packet){
$myPrettyStream->addPacket($packet);
}
所以我在代码注释中解释了我想要做什么。我的问题是:在我将所有数据包添加到 foreach 中的流后,我的所有Stream::packets
数组元素都将包含(引用)到$packet
我添加到流中的最后一个。
似乎 PHP在函数调用之间保留了$packet
我的函数内部的变量。addPacket(&$packet)
(这可能是有意的还是不好的优化?)无论我是&$packet
通过引用数组(基本上是引用引用&&$packet)还是简单地引用$packet
(&$packet)来传递变量,我认为这不应该是预期的行为。
但是,如果我不在函数内部进行引用,它可以工作:
public function addPacket(&$packet){
$this->packets[] = $packet;
}
请有人解释为什么这种行为是有意义的!
谢谢!
==================================================== ========================
解决方案
感谢您的正确答案,我模拟了一个行为相同的函数调用:
// try to emulate function call inside iteration
$packet = $packets[0];
$functionPacket = &$packet;
$packetsItem[0] = &$functionPacket; //functionpacket holds a reference to $packet
var_dump($packetsItem);
echo "\nsecond iteration\n";
unset($functionPacket);
$packet = $packets[1];
$functionPacket = &$packet;
$packetsItem[1] = &$functionPacket;
var_dump($packetsItem);
output:
array(1) {
[0]=>
&object(Packet)#1 (2) {
["time"]=>
int(1)
}
}
array(2) {
[0]=>
&object(Packet)#2 (2) {
["time"]=>
int(2)
}
[1]=>
&object(Packet)#2 (2) {
["time"]=>
int(2)
}
}