A few years ago I used to work with PHP and there’ve been many changes in PHP, especially on the OOP part.
Back then it was necessary to use the & operator at several places, especially when working with object instances (OOP was very rudimentary then) to avoid copying object instances.
With PHP 5.2 there seems to be a lot of improvement compared to 4.0 and I’m a little bit confused.
When do I have to use the & operator in PHP to avoid any unpleasant surprises from a Java programmer’s perspective?
Examples:
$a = (&)new MyClass(); //Necessary?
function factoryMethod() {
$a = (&)new MyClass(); //Necessary?
return (&) $a; //Necessary?
}
// Other cases?!
EDIT: By chance my examples don’t need the & operator at all. But where would I need it?
To make it short: nowhere in your examples.
In case we’re dealing with
objectsyou do not have to use the reference operator at all.If you’re dealing with other datatypes the most common reference operations are:
Passing by Reference
Returning References
Looping with
foreachBe careful as the last
unset()-call is important if your code uses$valueagain downstream.Whereas the first case (passing by reference) is much more common than the second case, e.g. especially when dealing with arrays: