In OOP, you usually do not get the behaviour you want if you don't pass by reference.
If you copy an object changes in state for the original object are not updated in the copy.
If you pass a reference to the object, there's only ever a single object which different vars point towards. Wherever one of the object's interface methods is called, and the original object changes state, you can be sure that all your other referenced vars reflect this new state. Usually that's what you want.
Suppose you have an ErrorLog class which you intend should gather any errors in the script and later log these to file. ErrorLog is used by a whole bunch of other objects.
If ErrorLog is passed around by reference you get the intended behaviour of a single errors class which collects info from all the other objects.
If the errors class was instead being copied to the other objects, you'd have to collect each of the separate errors classes (somehow) and log the contents of each in turn - very messy.
One of the best practical guides on OOP referencing comes from the
eclipse read me:
- To get Java-like object behavior, ALWAYS use references when:
- Creating objects : $object =& new Object;
- Passing objects : function receiveObject(&$object) { //... }
- Returning objects: function &returnObject() { return $object; }
PHP's default behavior is to create copies, which is almost always NOT what
you really want. When some object contains a reference to a second object
and you create a copy of the first object instead of a reference, this copy
will NOT share the reference to the second object, but will hold a copy of
that object instead. This can (and will) lead to strange and undesired
behavior. To summarize:
function &getNiftyComputationResult(&$iterator))
{
$result =& new NiftyComputationResult;
for ($iterator->reset(); $iterator->isValid(); $it->next())
{
$result->add($iterator->getCurrent());
}
return $result;
}
$it =& new ArrayIterator(array(8, 5, 3, 9, 6, 1, 7, 4, 2));
$result =& getNiftyComputationResult($it);
It takes a while to get used to, but it is truly the only way to correctly
handle objects in PHP 4 ('correctly' meaning 'Java-like' in this context).