Remember the first time you dabbled in C? Oh, the glorious typing, functions, and structs! Now do you remember the first time you ran in to a pointer? ‘*’, ‘&’, ‘->’ all made your hurt, but eventually you figured it out. It’s fortunate (depending how you look at it) that we don’t have need to dabble with pointers or references while web programming these days. However, PHP does allow us to passing things around by reference. It’s not used often, but when used correctly can be very beneficial to the quality of your code.

What are PHP references?

The first thing you need to know about PHP references is that they are not C references. You can’t do pointer arithmetic on them because they aren’t actually addresses. In PHP references are actually symbol table aliases. This means that you can have 2 variable names sharing the same variable content.

What can you do with references?

There are 3 things that you can do with PHP references.

Assign by reference.

Pass by reference.

Return by reference.

$x =& $y ; $x = 3 ; echo "X: $x , Y: $y " ; $x =& $y; $x = 3; echo "X: $x, Y: $y";

The above code sets $x and $y’s references to the same content area. Therefore, when $x is assigned 3, $y has access to the same data.

function add_item ( & $item ) { $item ++; } $totalItems = 0 ; for ( $i = 0 ; $i <; 5 ; $i ++ ) { add_item ( $totalItems ) ; } echo "Total items: $totalItems " ; function add_item(&$item) { $item++; } $totalItems = 0; for($i = 0; $i <; 5; $i++) { add_item($totalItems); } echo "Total items: $totalItems";

This code allows you to modify a variable’s value without ever returning anything. In this example I made a simple counter, but you can set the value of $item to anything and it should work out just fine.

class Test { public $count = 0 ; public function & getCount ( ) { return $this -> count ; } } $t = new Test ( ) ; $value = & $t -> getCount ( ) ; $t -> count = 25 ; echo $value ; class Test { public $count = 0; public function &getCount() { return $this->count; } } $t = new Test(); $value = &$t->getCount(); $t->count = 25; echo $value;

This code returns a reference to the public $count variable of the Test class. Generally this isn’t best practice, as it lowers the readability of the code.

Unsetting References

In the event that you want to free a variable from it’s reference to another, you can simply use the unset function.