Wednesday, September 29, 2010

References to Variables in php

By default, variables are assigned by value. In other words, if you were to assign
$aVariable to $anotherVariable, a copy of the value held in $aVariable would be
stored in $anotherVariable. Subsequently changing the value of $aVariable would
have no effect on the contents of $anotherVariable. Listing 4.2 illustrates this.
Listing 4.2: Variables Are Assigned by Value
1: <html>
2: <head>
3: <title>Listing 4.2 Variables are assigned by value</title>
4: </head>
5: <body>
6: <?php
7: $aVariable = 42;
8: $anotherVariable = $aVariable;
9: // a copy of the contents of $aVariable is placed in $anotherVariable
10: $aVariable = 325;
11: print $anotherVariable; // prints 42
12: ?>
13: </body>
14: </html>
This example initializes $aVariable, assigning the value 42 to it. $aVariable is then
assigned to $anotherVariable. A copy of the value of $aVariable is placed in
$anotherVariable. Changing the value of $aVariable to 325 has no effect on the
contents of $anotherVariable. The print statement demonstrates this by outputting
42 to the browser.
In PHP4, you can change this behavior, forcing a reference to $aVariable to be
assigned to $anotherVariable, rather than a copy of its contents. This is illustrated in

1: <html>
2: <head>
3: <title>Listing 4.3 Assigning a variable by reference</title>
4: </head>
5: <body>
6: <?php
7: $aVariable = 42;
8: $anotherVariable = &$aVariable;
9: // a copy of the contents of $aVariable is placed in $anotherVariable
10: $aVariable= 325;
11: print $anotherVariable; // prints 325
12: ?>
13: </body>
14: </html>
We have added only a single character to the code in Listing 4.2. Placing an
ampersand (&) in front of the $aVariable variable ensures that a reference to this
variable, rather than a copy of its contents, is assigned to $anotherVariable. Now
any changes made to $aVariable are seen when accessing $anotherVariable. In
other words, both $aVariable and $anotherVariable now point to the same value.
Because this technique avoids the overhead of copying values from one variable to
another, it can result in a small increase in performance. Unless your script assigns
variables intensively, however, this performance gain will be barely measurable.
Note References to variables were introduced with PHP4.

No comments:

Post a Comment