Categories
PHP Programming

PHP Dark Arts: References

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";

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";

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;

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.

$x =& $y;
unset($x);

By Jack Slingerland

Founder of Kernl.us. Working and living in Raleigh, NC. I manage a team of software engineers and work in Python, Django, TypeScript, Node.js, React+Redux, Angular, and PHP. I enjoy hanging out with my wife and son, lifting weights, and advancing Kernl.us in my free time.

One reply on “PHP Dark Arts: References”

Comments are closed.