Php 这是eval()的可接受用法吗?
我正在尝试使用内爆字符串作为运算符。作为一名PHP新手,eval()是迄今为止唯一有效的选项 我已经阅读了Php 这是eval()的可接受用法吗?,php,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
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
的事情作为解决方法
即使可以接受,如果您有任何改进建议,请告诉我。没有。。。你的想法太宽泛了。您有一个函数名数组,并且您跳得太远,无法将它们作为自由格式代码执行 实际上,函数名是有效的回调,使用
call\u user\u func()
执行这些回调更安全、更容易。因此,只需array\u map('call\u user\u func',$conditions)
即可将所有回调转换为它们的返回值
但请注意,您想要的条件是或类型。我们不需要运行每个回调,我们只需要执行它们,直到得到第一个true
one
这可以表示为:
$result = array_reduce( $callbacks, function ( $carry, $callback ) {
return $carry ?: (boolean) call_user_func( $callback );
}, false );
我已经投票决定将这个问题转移到stackoverflow,因为这个问题在这里是离题的,stackoverflow是询问有关通用php的问题的最佳场所。我希望你能在那里得到答案:-)我明白。然而,我希望能找到使用上述WordPress条件句的具体答案。@Rarst回答了我的问题。谢谢你,彼得。我太生疏了,没有意识到WordPress条件句和我的问题无关。没问题。很高兴你把它解决了。顺便说一句,这是一个很好的答案,我已经投了赞成票:-)谢谢你的帮助=)。我对PHP的理解还处于初级阶段,还没有找到任何教程系列可以帮助您掌握更高级的概念。