MCHatora MCHatora - 2 years ago 91
PHP Question

php extract() usage and purpose

I (think) I understand the function of php's extract() function. However, I was reading some code and I saw something like this:

extract(['a' => '', 'b' => '', 'c' => 1, 'd' => 0]);

My questions:

1: Is this functionally different from:

$a = ''; $b = ''; $c = 1; $d = 0;

2: What are the reasons for variable declaration/assignment using extract()?

Answer Source

Is this functionally different from...

No both lines of code are equivalent. extract returns values where the key is set to the variable name and the value is what that variable equals, which is depicted in each line of code making them functionally equivalent.

What are the reasons for variable declaration/assignment using extract()?

A reasonable use case would be using extract on a function that returns an array of values with known keys. Doing this saves you time in writing a line of declaration for each stored value. I say known keys because although using unknown keys is possible through using array_keys and variable variables, you start to enter a realm of questionable coding techniques by doing this.

Within the documentation of extract it states, "Do not use extract() on untrusted data...", which include user inputted data which may have been maliciously altered. Though this means using extract on $_POST is improper for a public version, there is nothing functionally wrong with doing this for testing or a personal project where you can guarantee the values of the $_POST are as expected.

Keep in mind that there is a level of ambiguity when using extract and if your program ever need be maintained at a later date, understanding what an extract statement is returning or finding the origin of variables that came from an extract may be difficult. extract has its uses within programs, but it should be accompanied with comments outlining what it is doing, to make future reference more clear.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download