I have my doubts whether the statement of the first paragraph is correct, in fact I don’t even know if it is clear.
What is the advantage of PHP objects being passed by default references?
Basically two:
- do not need to copy the object, which can often be a relatively costly operation because some objects tend to be a bit large (although for PHP this does not make so much difference and maybe they have done because other languages are like this);
- can modify the values of the object anywhere and this reflect throughout the application, exactly what you think is a defect is considered an advantage.
There are some advantages derived from this, such as being able to use polymorphism, avoid slicing, and others. A reference is a indirect, that gives more flexibility to do various things.
Rare cases where you don’t want a change to reflect on the object in a global way, and if you need to do this think you’re not doing something wrong. If you really need this it would be good to analyze whether this object plays a correct role in the system and whether it should not be formulated otherwise. Another question to consider is whether not being able to touch the object is something of his own and he himself should ensure the immutability or if it’s a one-off case that deserves a copy.
any change I made to the variable, also changed my object
This is not true, if you change the whole object in the variable will not move the other object. Precisely because an object is by reference if you change the reference you will be placing another object in the variable and therefore the original object will not be changed. Note that this change occurs only in the variable, so it passed as argument does not touch the argument, only the parameter that is the variable, so if you leave the method it no longer makes sense to wait for this change reflected in some other variable of the calling method.
This is actually the pattern of passing values of primitive types in most languages. Your example code doesn’t make much sense... If the argument arrived as a copy of the value, why would you need to assign to another variable
$bar
? It would be enough to return$foo
.– bfavaretto
It is worth remembering that even the
clone
PHP native only does the shallow (or shallow) copy of the object. If you need a deep (or full) copy you will have to manually implement through the method__clone
.– Woss