PHP按值传递对象 [英] PHP pass objects by value
本文介绍了PHP按值传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用PHP实现一个纯函数
I'd like to implement a pure function in PHP
如何通过值而不是通过引用传递对象?
How do I pass an object by value and not by reference?
换句话说,这是预期的输出:
In other words, this is the expected output:
function change($obj) {
$obj->set_value(2);
}
$obj = new Object();
$obj->set_value(1);
change($obj);
echo $obj->get_value(); // 1
推荐答案
在此处阅读:
http://php.net/manual/en/language.oop5.cloning.php
您真的不应该按值传递,因为那样就需要深层复制.深度克隆,或为参数分配的疯狂数量.
you really shouldn't pass by value, as that would require a deep copy aka. deep clone, or an insane amount allocated for for parameters..
如果您确实想要,答案是:首先是深层副本,然后将引用传递给副本.
if you really want to, the answer is: first deep copy, then pass a reference to the copy.
这篇关于PHP按值传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文