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
这是一个类型提示,它告诉我们这个函数接受参数$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)
这是一个非常简单的例子,但我希望它可以帮助您理解这个想法。