Friday 7 October 2011

php references and some unexpected behaviour

I had some functions that would iterate over a tree that was several levels deep and augment it with new fields before it was passed to a view. This seemed like a pretty nice idea since it meant I could easily add new functions with their own customisations later.

Everything worked well for a while but then someone noticed the final row looked a bit strange.

It's best demonstrated with this contrived example:

protected function wtf()
{
    $array = array(10, 10, 10);

    foreach($array as &$value) {
        $value++;
    }
  
    foreach($array as $value) {
        $value++;
    }

    var_dump($array);
}

There's no real reason for using a reference in the above example but you might expect a result similar to this:

array
  0 => int 12
  1 => int 12
  2 => int 12

What you'll get is the following:

array
  0 => int 11
  1 => int 11
  2 => &int 13

I showed my boss and his response was "Didn't you read the Zend Certification Guide? It has a whole chapter about this.."

No comments:

Post a Comment