Friday, February 29, 2008

eval is still evil

Here is an interesting code snippet from the simplicity php framework:

//...
static public function check($path=false) {
if (!self::loadFiles($path)) return false;

$arr = "";
$apath = explode('.',$path);
foreach ($apath as $pt) {
$arr .= "['{$pt}']";
}

$var = 'self::$_settings'.$arr;
$eval = "return isset({$var}) ? true : false;";
return eval($eval);
}
//...


What happens? This code traverses through an multidimensional array with N dimensions.
Yes, recursion is sometimes tedious. But if i can avoid an eval call, i avoid it! The solution without eval is not longer and not much harder to understand and written in nearly the same time:

$data['foo']['baz']['wtf'] = 'whupass';
$path = 'foo.baz.wtf';

$p = explode('.', $path);
$value = $data;
while ($k = array_shift($p)) {
$value = $value[$k];
}

echo "$value\n";


Cute, isn't it?

1 comment:

Anonymous said...

Amazing, just found this post. Yes, that wasn't the best piece of code I have ever written. That's what you get for coding at 3am. Simplicity is very different now that it was when you last looked at it. Would be interested to hear your thoughts.

http://www.simplicityphp.com

Cheers

John