PHP:类型提示-`Closure`和`Callable`之间的区别 [英] PHP: Type hinting - Difference between `Closure` and `Callable`

查看:83
本文介绍了PHP:类型提示-`Closure`和`Callable`之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,如果我们希望运行某些回调函数,则可以使用ClosureCallable作为类型提示.例如:

I noticed that I can use either of Closure or Callable as type hint if we expected some callback function to run. For example:

function callFunc1(Closure $closure) {
    $closure();
}

function callFunc2(Callable $callback) {
    $callback();
}

$function = function() {
    echo 'Hello, World!';
};

callFunc1($function); // Hello, World!
callFunc2($function); // Hello, World!

问题:

这里有什么区别?换句话说,什么时候使用Closure和什么时候使用Callable OR,它们具有相同的目的?

What's the difference here ? In other words when to use Closure and when to use Callable OR they serve the same purpose ?

推荐答案

区别在于, Closure 必须是匿名函数,其中 callable 也可以是普通函数

The difference is, that a Closure must be an anonymous function, where callable also can be a normal function.

您可以使用下面的示例查看/测试它,您将看到第一个错误:

You can see/test this with the example below and you will see that you will get an error for the first one:

function callFunc1(Closure $closure) {
    $closure();
}

function callFunc2(Callable $callback) {
    $callback();
}

function xy() {
    echo 'Hello, World!';
}

callFunc1("xy"); // Catchable fatal error: Argument 1 passed to callFunc1() must be an instance of Closure, string given
callFunc2("xy"); // Hello, World!

因此,如果您只想键入提示匿名函数,请使用:Closure,并且如果您还希望允许普通函数,请使用callable作为类型提示.

So if you only want to type hint anonymous function use: Closure and if you want also to allow normal functions use callable as type hint.

这篇关于PHP:类型提示-`Closure`和`Callable`之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆