I was recently reading this thread, on some of the worst PHP practices.
In the second answer there is a mini discussion on the use of extract()
, and im just wondering what all the huff is about.
I personally use it to chop up a given array such as $_GET
or $_POST
where I then sanitize the variables later, as they have been conveniently named for me.
Is this bad practice? What is the risk here? What are your thoughts on the use of extract()
?
I find that it is only bad practice in that it can lead to a number of variables which future maintainers (or yourself in a few weeks) have no idea where they're coming from. Consider this scenario:
extract($someArray); // could be $_POST or anything
/* snip a dozen or more lines */
echo $someVariable;
Where did $someVariable
come from? How can anyone tell?
I don't see the problem in accessing the variables from within the array they started in, so you'd really need to present a good case for using extract()
for me to think it's worth it. If you're really concerned about typing out some extra characters then just do this:
$a = $someLongNameOfTheVariableArrayIDidntWantToType;
$a['myVariable'];
I think the comments here on the security aspects of it are overblown somewhat. The function can take a second parameter that actually gives you fairly good control over the newly created variables, including not overwriting any existing variables (EXTR_SKIP
), ONLY overwriting existing variables (so you can create a whitelist) (EXTR_IF_EXISTS
), or adding prefixes to the variables (EXTR_PREFIX_ALL
).