这是eval()的可接受使用吗?

时间:2014-12-02 09:02:11

标签: php

我正在尝试使用内爆字符串作为运算符。作为一个PHP新手,到目前为止,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那样做一些解决方法。

即使可以接受,如果您对如何改进它有任何建议,请告诉我。

1 个答案:

答案 0 :(得分:2)

Nooo ......你的想法太宽泛了。你有一系列的函数名,你跳得太远而无法执行 freeform 代码。

实际上,函数名称是有效的回调,使用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 );
相关问题