Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

References

When you use the = (assignment) operator, PHP performs a "copy assignment"—it takes the value from operand two and copies it into operand one. While this is fine for most purposes, it doesn't work when you want to be able to change operand two later on and have operand one also change.

In this situation, references are helpful; they allow you to have two variables pointing to the same data. Once two variables are pointing to the same data, you can change either variable and the other one will also update. To assign by reference, you need to use the reference operator (&) after the equals operator (=), giving =&.

Tip

Perl programmers should not confuse the PHP references with Perl references. Instead, the equivalent in Perl and some other languages is called aliasing.

Here's how it looks in PHP:

    $a = 10;
    $b =& $a;
    print $a;
    print $b;
    ++$a;
    print $a;
    print $b;
    ++$b;
    print $a;
    print $b;

Here we're using the reference operator to make $b point to the same value as $a, as can be seen in the first two print statements. After incrementing $a, both variables are printed out again, and both are 11, as expected. Finally, to prove that the relationship is two-way, $b is incremented, and again both $a and $b have been updated with the one call.

Warning

As of PHP 5, objects are passed and assigned by reference by default. Technically, each object has a "handle," which uniquely identifies that object. When you copy an object, you are actually copying its object handle, which means the copy ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page