User Tools

Site Tools


php:phprefexplained

PHP REFERENCES EXPLAINED WITH GRAPHICS

What are references?

PHP references allow you to make two variables to refer to the same content. To make a reference, we'll use ampersand sign (&).
References aren't pointers ! (as in C). Instead, they are symbol table aliases.

STEP 1

 Step 1

First operations:

(1) create a variable $a with content 'Joe'
(2) make a reference to it, so give an other name ($b) to content 'Joe'

$a = 'Joe'; //(1)
$b = &$a; //(2)

Both $a and $b shows 'Joe'.

STEP 2

 Step 2

Operations: (1) create a variable $a with content 'Joe'
(2) make a reference $b to $a
(3) assign 'Bob' to $b

echo $a; // it prints “Bob”
echo $b; // it prints “Bob”

STEP 3

 Step 3

Operations: (1) create a variable $a with content 'Joe'
(2) make a reference $b to $a
(3) create a variable $c with content 'Ron'
(4) make new reference for $b to $c

echo $a; // it shows Joe
echo $b; // it shows Ron
echo $c; // it shows Ron

When you unset the reference, you just break the binding between variable name and variable content. This does NOT mean that variable content will be destroyed.

STEP 4

 Step 4

Operations: (1) create a variable $a with content 'Joe'
(2) make a reference $b to $a
(3) unset $b

echo $a; // it shows Joe
echo (isset ($b) ? “set”:unset); // it shows unset

STEP 5

Operations:

(1) repeat first two steps of STEP 4

$a = 'Joe';
$b = &$a;

(2) assign null to $a

$a = null;

(3) assign again a value to $a

$a = 'Another Joe';

If we'll check after step2,

echo (isset ($a) ? “set”:unset); // it shows unset
echo (isset ($b) ? “set”:unset); // it shows unset

and after step3

echo (isset ($b) ? “set”: “unset”); // it shows set

So, if you want to break the linkage you must use 'unset' and not 'null'.

php/phprefexplained.txt · Last modified: 2013/03/16 17:40 (external edit)