我刚刚从php.net中了解了可调用类型,并假定使用callable
关键字应允许将该函数作为参数传递给另一个函数。但是,我正在警告。这是我尝试过的:
<?php
function helloWorld()
{
echo 'Hello World!';
}
function handle(callable $fn)
{
$fn();
}
handle(helloWorld); // Outputs: Hello World!
?>
但是,有时会出现以下错误:
Parse error: syntax error, unexpected 'function' (T_FUNCTION), expecting variable (T_VARIABLE)
有时
Warning: Use of undefined constant helloWorld - assumed 'helloWorld' (this will throw an Error in a future version of PHP) in C:\Projects\Sandbox\myphp on line 12
Q1。为什么php期望helloWorld
是一个变量,而该变量已经被明确定义为一个函数。Q2。显然,在函数定义中删除关键字callable
没有什么区别。为什么?
您应该将引号放在引号中,如下所示:
handle('helloWorld');
而不是
handle(helloWorld);
[C0状态指出“ PHP函数以其名称作为字符串传递”。