关键字"callable"在PHP中做什么

S. *_*ody 10 php callable type-hinting function-declaration type-declaration

更确切地说,函数声明参数中使用的"callable".喜欢下面这个.

function post($pattern, callable $handler) {
    $this->routes['post'][$pattern] = $handler;
    return $this;
}
Run Code Online (Sandbox Code Playgroud)

它对我们有什么好处?

为什么以及如何使用它?

也许这对你来说非常基础,但是,我已经尝试过寻找它而我却得不到任何答案.至少,我无法理解.

希望得到一个假人的答案.我是编码的新手...... XD

编辑:这是我从上面复制上述代码的链接:link

ent*_*erd 8

callable类型允许我们将回调函数传递给被调用的函数。也就是说,回调函数参数允许被调用的函数动态调用我们在callable函数参数中指定的代码。这很有用,因为它允许我们将要执行的动态代码传递给函数。

例如,您可能想要调用一个函数,而该函数接受一个名为 的回调函数log,它将以您想要的自定义方式记录数据。

我希望这是有道理的。有关详细信息,请参阅此链接


Sha*_*hin 5

这是一个类型提示,它告诉我们这个函数接受参数$handler作为函数,看这个例子来澄清事情:

function helloWorld()
{
   echo 'Hello World!';
}
function handle(callable $fn)
{
   $fn(); // We know the parameter is callable then we execute the function.
}

handle('helloWorld'); // Outputs: Hello World!
Run Code Online (Sandbox Code Playgroud)

这是一个非常简单的例子,但我希望它可以帮助您理解这个想法。