PHP pass objects by value

梦想的初衷 提交于 2021-02-05 09:27:55

问题


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

回答1:


read here:

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.



来源:https://stackoverflow.com/questions/29962097/php-pass-objects-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!