[nycphp-talk] Variable composition: ${'foo'.$i}
Anthony Ferrara
ircmaxell at gmail.com
Fri Jan 31 12:11:04 EST 2014
Chris,
On Fri, Jan 31, 2014 at 10:08 AM, Chris Snyder <chsnyder at gmail.com> wrote:
> On Thu, Jan 30, 2014 at 12:12 PM, Jerry B. Altzman <jbaltz at altzman.com>wrote:
>
>>
>> 'Variable variables' aren't pure evil; they just provide a level of
>> indirection that allows for fine-grained loss of control at runtime.
>>
>
> Not only are they not evil, they're necessary for a lot of Don't Repeat
> Yourself optimizations.
>
Variable-variables as put here are not necessary in any situation. In
general they are dangerous, and a potential security hole. If you MUST
break down to native variables, use an array, and then extract() with the
"overwrite" flag as false (to prevent potential issues).
http://us2.php.net/extract
> I use this pattern all the time:
>
> foreach( array('pages', 'posts', 'comments') AS $collection ) {
> ${$collection} = $model->load( $collection );
> // do more stuff with ${$collection} here
> $template->assign( ${$collection}, $collection );
> }
>
Yes, and that's significantly worse than:
$container = array();
foreach( array('pages', 'posts', 'comments') AS $collection ) {
$container[$collection] = $model->load( $collection );
// do more stuff with $container[$collection] here
$template->assign( $container[$collection], $collection );
}
It's even more clear, since it shows outright where the data is. You can
tell instantly with any read where a variable was set.
Using variable-variables, you have literally no idea until runtime
(stepping through with a debugger) what area of code touches what variable.
Without them (using arrays or objects) you can clearly see *what* container
is being used, if not the specific element of it.
It's a little bit harder to read until you get used to it, but because it's
> DRY it's much easier to manage over time.
>
Many a great evil in programs have been done in the name of DRY. DRY !=
easier to manage. Clean coding with a focus on readability improve
maintainability in the long term. Hacks to save a few characters of writing
at the expense of cognitive load do not.
In short, the only form of variable-variables that I believe should
**ever** be used are variable object property/method references:
$obj->$property = blah;
$obj->$method();
Any other usage is simply mis-using variables where you should use a more
appropriate data structure (like an array or object)...
Anthony
> _______________________________________________
> New York PHP User Group Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> http://www.nyphp.org/show-participation
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20140131/dd3c7861/attachment.html>
More information about the talk
mailing list