0

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)
{

}
Nate
  • 26,164
  • 34
  • 130
  • 214

1 Answers1

3

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.

Mike B
  • 31,886
  • 13
  • 87
  • 111
  • Wouldn't that degrade performance? (I have several dozen objects that each need to be independently passed to about half a dozen different functions) – Nate Jul 06 '12 at 19:01
  • 1
    @Nate PHP uses [copy-on-write](http://en.wikipedia.org/wiki/Copy-on-write) so AFAIK it won't be a waste of a variable unless you modify the object. – Mike B Jul 06 '12 at 19:02
  • So if I pass the object with the `clone` keyword beforehand, will it copy the object without calling the object's constructor? Do I have to write a `__clone() method`? – Nate Jul 06 '12 at 19:08
  • @Nate It won't invoke the constructor. The `__clone()` method is optional.. only needed if you wanted to do things when an object is cloned. – Mike B Jul 06 '12 at 19:10