PHP Function of the Day (2011-9-28): extract

[fphp]extract[/fphp] is a curious function - taking the members of an array and making them local variables. So given an array with members ‘foo’, ‘bar’ and ‘mar’, calling extract($array) will create variables $foo, $bar, and $mar. If these variables already existed they’ll be overwritten. Calling extract on the $GLOBALS array will replicate the effect of the register_globals.

So it goes without saying misusing extract is dangerous. What’s it good for? Personally, I use it for templating, to form a hard barrier between the variables visible to the template and those which aren’t. Consider this rudimentary template function

<?php

function parseTemplate( $template, $output = array() ) {
  extract($output);
  ob_start()
  include($template);
  return ob_get_clean();
}

This function allows you to create a template who’s variables have their own “scope” separate from the rest of the code. This sort of separation is vital to design patterns. We separate code in this manner in order to reduce the number of interactions in the code we have to test - in so doing we make the code more easily tested. If a template is free to reference any variable in the program then changing any variable has to be tested against that template. With this approach though we can reduce what the template touches.

By itself the function above isn’t that useful. Within a class though the advantages increase. But that’s outside the scope of function of the day.

I’m nearing the end of my initial list of functions to cover. PM me with suggestions. Otherwise, in a week or two I’m going to start overviewing classes with each method of the class being the function of the day, starting with PDO.