7.5. Assigning Object References

Problem

You want to link two objects, so when you update one, you also update the other.

Solution

Use =& to assign one object to another by reference:

$adam = new user;
$dave =& $adam;

Discussion

When you do an object assignment using =, you create a new copy of an object. So, modifying one doesn’t alter the other. But when you use =&, the two objects point at each other, so any changes made in the first are also made in the second:

$adam = new user;
$adam->load_info('adam');

$dave =& $adam;
$dave->load_info('dave');

The values in $adam are equal to those of $dave.

See Also

Recipe 7.5 for more on copying object; documentation on references at http://www.php.net/references.

Get PHP Cookbook 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.