r/PHPhelp • u/leonstringer • Dec 06 '24
Does object param with '&' prefix do anything?
If you pass an object to a function it's passed by reference (technically an identifier for the object). So if the parameter name is prefixed with & does that make any difference?
For example with:
function myfunc1(stdClass $o) {
$o->myproperty = "test";
}
function myfunc2(stdClass &$o) {
$o->myproperty = "test";
}
$o = new stdClass();
myfunc1($o);
echo "$o->myproperty\n";
myfunc2($o);
echo "$o->myproperty\n";myfunc1() and myfunc2() appear to be functionally identical.
Is there any actual difference? Is myfunc2() "wrong"? Is the & just redundant?
3
Upvotes
10
u/MateusAzevedo Dec 06 '24
There is a small but important difference: by using
&the variable itself is a reference and this has a consequence:Example
So the best way to describe object behavior is: the object handler/pointer is passed by value, but both vars point to the same memory address/object, so that's why it behaves like by ref. By using
&the variable is a reference to the outer variable.1
u/leonstringer Dec 09 '24
Thanks for all the replies (I couldn't post over the weekend for some reason).
It seemed a silly question but I got some great answers which improved my understanding.
1
u/BarneyLaurance Dec 06 '24
Here's a demo to show the difference: https://3v4l.org/5FciZ#v8.4.1
1
u/Apprehensive_Ebb_346 Dec 07 '24
U are passing an object by reference and not by value
-2
u/bkdotcom Dec 06 '24 edited Dec 07 '24
The & is pointless. Objects are passed by reference (technically a reference to the object is passed by value)
In addition I would say it's wrong. In general, passing non-objects around by reference is a code smell.
edit: ¯_(ツ)_/¯
where did I go wrong?
-4
u/itemluminouswadison Dec 06 '24 edited Dec 06 '24
Yes it is redundant. Scalars (numbers, strings, bool) are passed by value. Everything else is by reference
edit: arrays are also by value