如何调用常量作为函数名称? [英] How to call a constant as a function name?
问题描述
在PHP中,您可以通过在变量内调用函数名称来调用函数.
In PHP, you can call functions by calling their name inside a variable.
function myfunc(){ echo 'works'; }
$func = 'myfunc';
$func(); // Prints "works"
但是,您不能使用常量来做到这一点.
But, you can't do this with constants.
define('func', 'myfunc');
func(); // Error: function "func" not defined
有一些解决方法,例如:
There are workarounds, like these:
$f = func;
$f(); // Prints "works"
call_user_func(func); // Prints "works"
function call($f){ $f(); }
call(func); // Prints "works"
callable 代码>
说:
PHP函数的名称以字符串形式传递.可以使用任何内置的或用户定义的功能,语言构造除外.
A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs.
似乎没有关于常量值不可调用的信息.
There seems to be nothing about constant values not being callable.
我也尝试检查它,当然,
I also tried to check it, and of course,
var_dump(is_callable(func));
打印 bool(true)
.
现在,是否有这种解释的解释?据我所知,所有解决方法都依赖于将常量值分配给变量,为什么不能调用常量?
Now, is there an explanation as to why is it this way? As far as I can see all the workarounds rely on assigning the constant value to a variable, by why can't constant be called?
再一次,只是为了使其非常清晰,我不需要调用该函数的方法,甚至在此处提供了一些方法.我想知道为什么 PHP不允许直接通过常量调用函数.
And again, just to make it super clear, I don't need a way to call the function, I even presented some there. I want to know why PHP doesn't allow calling the function directly through the constant.
推荐答案
由于您询问了原因/原因,我猜唯一的答案(可能不会满足您)是:
因为尚未在 https://wiki.php.net/rfc 上提出,讨论和接受,
Since you asked for the why/reason I guess the only answer (which will probably not satisfy you) is:
Because it hasn't been proposed, discussed and accepted on https://wiki.php.net/rfc .
这篇关于如何调用常量作为函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!