Memory Management

In PHP 4, when you copy a variable or pass it to a function, you don’t transfer the original variable. Instead, you pass a copy of the data stored in the variable. This is known as pass-by-value because you’re copying the variable’s values and creating a duplicate.

As a result, the new variable is completely disassociated from the original. Modifying one doesn’t affect the other, similar to how calling $zeev->setName( ) didn’t affect $rasmus in the earlier example.

Object References

Objects in PHP 5 behave differently from other variables. You don’t pass them by value, like you do with scalars and arrays. Instead, you pass them by reference. A reference, or object reference, is a pointer to the variable. Therefore, any alterations made to the passed object are actually made to the original.

Here’s an example:

$rasmus = new Person;
$rasmus->setName('Rasmus Lerdorf');

$zeev = $rasmus;
$zeev->setName('Zeev Suraski');

print $rasmus->getName( );
Zeev Suraski

In this case, modifying $zeev does change $rasmus!

This is not what occurs in PHP 4. PHP 4 prints Rasmus Lerdorf because $zeev = $rasmus causes PHP to make a copy of the original object and assign it to $zeev.

However, in PHP 5, this command assigns $zeev a reference to $rasmus. Any changes made to $zeev are actually made to $rasmus.

A similar behavior occurs when you pass objects into functions:

function editName($person, $name) { $person->setName($name); } $rasmus = new Person; $rasmus->setName('Rasmus ...

Get Upgrading to PHP 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.