Passing an object by const reference?

主宰稳场 提交于 2019-12-24 20:36:43

问题


In C++ when you want a function to be able to read from an object, but not modify it, you pass a const reference to the function. What is the equivalent way of doing this in php?

I know objects in php5 are passed by reference by default, but for readability I think I will continue to use the ampersand before the variable name, like this:

function foo(&$obj)
{

}

回答1:


If you want to pass an object but not by reference you can clone the object beforehand.

<?php
function changeObject($obj) {
  $obj->name = 'Mike';
}

$obj = new StdClass;
$obj->name = 'John';

changeObject(clone $obj);
echo $obj->name; // John

changeObject($obj);
echo $obj->name; // Mike

I know objects in php5 are passed by reference by default, but for readability I think I will continue to use the ampersand before the variable name

That's your call but I find that would simply make it read more like C++. Alternativly, you can show that an object is being passed in by using type-hinting in your function definition:

function foo(StdClass $obj)
{

}

Once it's clear that $obj is an object it can be assumed that it's being passed by reference.



来源:https://stackoverflow.com/questions/11368145/passing-an-object-by-const-reference

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