问题
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"
The PHP documentation on callable says:
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));
prints 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?
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.
回答1:
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 .
回答2:
This works since PHP 7.0. The only things is that you have to use more expressive syntax, so that PHP knows you mean to execute myfunc
instead of func
.
<?php
function myfunc(){ echo 'works'; }
define('func', 'myfunc');
(func)();
Try this online: https://3v4l.org/fsGmo
The problem with PHP is that constants and identifiers are expressed as the same thing in the tokenizer. See online how this syntax is tokenized by PHP
When you use parentheses to change precedence of operations on the constant, you tell PHP to first parse the constant and use its value to execute the function. Otherwise PHP will think that func
is the name of your function.
回答3:
When trying to call a constant as a function, like so:
define('FUNC', 'myFunction');
function myFunction()
{
echo 'Oh, hello there.';
}
FUNC(); // Fatal error: Call to undefined function FUNC()
Will cause the PHP Interpreter to expect a function called FUNC. Hence the error Fatal error: Call to undefined function FUNC()
Despite the type of the constant FUNC being callable
, calling it as a function won't work. Simply because PHP expects a function named FUNC.
So without a workaround, you won't be able to call a function directly through a constant.
回答4:
Try this one. Works for me.
constant('func')();
constant()
function returns value of the constant, in your case its myfunc
, then apply round brackets ()
and you will have valid myfunc()
call.
来源:https://stackoverflow.com/questions/22665619/how-to-call-a-constant-as-a-function-name