PHP 通过引用传递问题


PHP Pass by Reference Issue

所以我遇到了一个奇怪的问题,其中函数不是通过传递引用参数定义的,而是以我无法解释的方式更改对象。 我已经验证了函数定义不会一次又一次地通过引用传递。 我从数据库中检索了一个对象。 然后,我对该初始对象运行了一个分析函数。 我已将对象复制到另一个变量。 然后我在副本而不是原件上运行不同的分析函数。 运行第二个分析函数似乎会改变第一个变量对象。关于这里可能发生的事情的任何想法。我一直在尝试调试它几个小时,但我无法解释这种行为。 我宁愿不发布实际功能,因为它们是专有信息,但是,我可以私下发送它们以获得帮助。 我衷心感谢您花时间帮助我。

//get object from db
$resp= json_decode($ln->getResponseFromDb($resultid)); 
//run pwf analysis function
$resp = $ln->pwfBGCheck($resp);
//show result after pwf
print_r($resp->pwf);
/* shows
* stdClass Object ( [status] => p [reason] => Person has no c record. ) 
*/ 
//copy to another variable
$r2 = $resp;
//run pwf for s record other variable so it is not touching the first one!
$r2 = $ln->pwfBGCheckSexOffender2($r2);
echo '<BR>this is first variable<BR>';
print_r($resp->pwf);
/* copies from second to first for some reason... no pass by reference on this call...       resp variable has not been touched!
* stdClass Object ( [status] => p [reason] => Person has no s record. ) 
*/ 
echo '<BR>this is second<BR>';
print_r($r2->pwf);
/* returns
* stdClass Object ( [status] => p [reason] => Person has no s record. )
*/

因为 PHP5 对象总是通过引用传递。如果要获取对象的副本,则必须使用克隆。

对象和引用

PHP 中

通常的按值赋值行为的例外发生在对象上,这些对象在 PHP 5 中通过引用赋值。可以通过克隆关键字显式复制对象。

赋值运算符

你也可以使用 json_decode($json, true);(而不是 json_decode($json); )来获取 assoc array(而不是 stdClass )。

并且参考文献不会有任何问题。

在永远发疯之后...我找到了这个解决方案:

$r2 = unserialize(serialize($resp));

我知道这并不理想,因为性能会受到影响,但我在截止日期前,需要尽快创建一个可行的解决方案。 我相信这个问题仍然存在,因为即使是正在复制的变量也是通过引用传递的。如果有人想出更好的选择,我愿意接受另一个可行的解决方案。 谢谢!

也。。。由于序列化的其他一些问题(libxml 无法序列化),此解决方案不起作用...但后来我想到了

$r2 = json_decode(json_encode($resp));

这实际上起到了作用!