PHP by reference

December 7th, 2013

I've known for some time that in PHP you can pass by reference like this:

function doSomthing($a, &$b) {
  ...
}

By defining a function this way the $b parameter will be passed by reference, meaning if you change $b inside the function it will also be changed for the caller. An example:

function increase(&$x) {
  $x++;
}

$num = 1;
increase($num);
print $num;

This will output "2", since $x in the increase function is referencing the same as $num.

Today I learned that you can by reference in two other ways as well.

Return reference

You can return a reference to a value instead of the value itself by putting the ampersand in front of the function name like this:

function &createObject() {
  $obj = new stdClass();
  $obj->max = 5;
  return $obj;
}

I'm not really sure what the benefit of this will be, but there you go.

Loop with reference

Now this one is cool. I didn't think about for loops as being able to do anything but loop through iterable content, but you can also pass by reference in a loop like this:

foreach($list as &$item) {
  $item->addValue($value);
}

This will have the same effect as passing a variable to a function by reference. When the $list have been looped over, the items in the list will be updated.

Categories

IT

Tags

php