这不是“In PHP, how do I check if a function exists?”的副本。
$syntax_only = true
允许
语言结构(例如empty
),虽然它也允许
random_function_that_does_not_exist
。如何检查输入是否可调用,既可以作为现有函数,也可以作为函数的语言结构?
答案 0 :(得分:1)
由于empty
总是并且是一种无法使用变量函数调用的语言构造,因此想要在其上使用function_exists
是没有意义的。即使function_exists
可行,也无法编写此代码:
$func = 'empty';
if (function_exists($func)) {
$func($var);
}
调用empty()
的唯一方法是在源代码中直接编写它。您无法使用变量函数调用它,只能使用list() =
或/
来执行此操作。
你能做的最好的事情是:
if (function_exists('empty')) {
empty($foo);
}
但是因为empty
总是存在,测试它的重点是什么?
如果您想制作验证规则,只需编写自己的函数:
function isEmpty($value) {
return !$value;
}
$rule = 'isEmpty';
这完全是一回事。
或者您在规则执行中将empty
作为特例:
function validate($rule, $value) {
switch ($rule) {
case 'empty' :
return !$value;
default :
if (!function_exists($rule)) {
throw new InvalidArgumentException("$rule does not exist");
}
return $rule($value);
}
}
答案 1 :(得分:1)
您提出的问题存在各种潜在问题。但是,如果我理解正确,您只想知道somename
是否可以像somename('someinput')
一样调用。
如果这是真的,那么您似乎需要使用function_exists
和List of Keywords语言结构的手动查找的组合。
或许这样的事情:
function canICall($function) {
$callableConstructs = array("empty","unset","eval","array","exit","isset","list");
return function_exists($function) || in_array($function, $callableConstructs);
}
$callableConstructs
数组未完成,请查看“关键字列表”页面以构建它。
是的,它是hackish,但没有内置的方式在PHP中执行此操作我没有看到其他选项。
请注意,仅仅因为你可以调用类似函数的东西,不使它成为一个函数,也不意味着它表现< / em>就像其他方面的功能一样。
你无法动态调用它:
$var = "empty";
$var('someinput'); // Does NOT work
这也不起作用:
call_user_func('empty', $foo);
你可能在eval
电话中使用它,但我希望你能理解为什么这可能是危险的大量原因。