A warning about extract() and null values.

A warning about extract() and null values.

This might be an actual Zend2 Engine bug, but it’s bad programming practice, so I’m sharing it here instead.

I often work in envrionments where E_STRICT (which would prevent errors like this) isn’t on, and I don’t have access to change it. I also use a very simple template class that in a nutshell works like this:

[php]
$t = new Template(‘somefile.php’);
$t->title = $title;
$t->body = $body;
$t->display();
[/php]

display() more or less looks like this:

[php]
function display(){
extract(get_object_vars($this),EXTR_REFS);
ob_start(); include $this->templateFileName;
return ob_get_clean();
}
[/php]

If any of the assigned values are null (let’s say that in this case $title wasn’t initialized above) it causes the engine to do all sorts of incredibly whacky stuff like certifiably lose track of variables in an incredibly inconsistent way. I traced the problem down to the fact that it’s using the EXTR_REFS flag. I assume that in PHP’s internal variable storage or reference counting mechanism, that trying to extract null references makes it lose track or count of something or rather.

In a nutshell, if you start getting wierd behavior when using extract() make sure that the array or object you are trying to get variables out of doesn’t contain null keys or values!