Recipe 7.9. Assigning Object References

7.9.1. Problem

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

7.9.2. Solution

Use = to assign one object to another by reference:

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

7.9.3. Discussion

When you do an object assignment using =, you don't create a new copy of an object, but a reference to the first. So, modifying one alters the other.

This is different from how PHP 5 treats other types of variables, where it does a copy-by-value. It is also different from PHP 4, where all variables are copied by value, regardless of their type.

So where you used to use =& in PHP 4 to make two objects point at each other, you can now use only =:

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

Now $dave and $adam are two names for the exact same object.

7.9.4. See Also

Recipe 7.10 for more on cloning objects; documentation on references at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: