如何使用可调用伪类型将函数用作 php 中另一个函数的参数?

How to use a function as an argument of another function in php using callable pseudo type?

我刚刚从 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);

PHP Docs for callable 指出 "A PHP function is passed by its name as a string"。