这是一个可接受的使用eval()吗?
问题描述:
我试图使用一个内爆字符串作为运算符。作为一个PHP新手,到目前为止,eval()是唯一可行的选项。这是一个可接受的使用eval()吗?
我已阅读eval()
的其他问题。在大多数情况下,人们试图允许用户输入实际的代码,这不是我在这里做的。
这就是:
/*
* Get user choices from a multiple-select customizer custom control.
* Setting's choice values are the names of WordPress conditional tags.
* Each choice set is given as 'key'=>'label' NOT 'key'=>'function'
* so I'm limited to using strings here, e.g. is_front_page, is_singular.
* The result will be a linear array, e.g. array(is_front_page, is_singular).
*/
$conditions = get_theme_mod('theme_setting');
/*
* Here's where my trouble begins.
* I need to append `()` to each array value using array_walk. */
array_walk($conditions, function(&$value, $key) { $value = $value . '()'; });
/*
* Next I implode the array values to insert the or operator
* So instead of "is_front_page, is_singular", I'd end up with
* "is_front_page() || is_singular()"
*/
$conditions = implode(' || ', $conditions);
/* The previous step is NOT usable, in my novice experience, hence eval() */
eval('$conditions = ' . $conditions . ';');
/* Eval makes the following usable */
if($conditions) {
// do stuff here
}
我希望这是可以接受的,因为我不会允许来自用户代码输入,我的主题设置为静态的,所以我实际上不能这样做$conditions === true
为解决方法。
即使可以接受,请让我知道如果您有任何建议如何改善它。
答
Nooo ...你的想法太宽泛了。你有一个函数名称数组,你跳得太远,不能执行它们作为自由形式代码。
其实功能名称是有效的回调和那些更安全和更容易执行call_user_func()
。所以简单地array_map('call_user_func', $conditions)
会将所有的回调变成它们的返回值。
但请注意,您所需的条件是OR型。我们不需要每回调运行,我们只需要执行它们,直到我们获得第一个true
之一。
这可以表示为:
$result = array_reduce($callbacks, function ($carry, $callback) {
return $carry ?: (boolean) call_user_func($callback);
}, false);
+0
感谢您的帮助=)。我理解PHP在一个基本的水平,并没有发现任何教程系列,帮助您掌握更多的先进理念。 – 2014-12-02 18:32:23
我已经投了移动这StackOverflow的,因为这问题是题外话这里,和计算器是询问有关通用PHP问题的最佳场所。我希望你能在那里得到答案:-) – 2014-12-02 09:15:30
我明白了。不过,我希望能够得到上述使用WordPress条件的具体答案。 – 2014-12-02 09:23:27
@Rarst回答了我的问题。谢谢彼得。我太绿了,无法意识到WordPress的条件与我的问题无关。 – 2014-12-02 18:36:05