PHP 中`Closure`和`Callable`的区别以及在 Redis 订阅方法中的使用

它们的不同之处:Closure 必须是匿名函数,  callable 同时还可以为常规函数。
以下的例子中第一个会出现错误:

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

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

function xy() {
    echo 'Hello, World!';
}
$function = function() {
    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!

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

//从php7.1开始可以使用以下代码转换
callFunc1(Closure::fromCallable("xy"))

其中callable参数可以为

is_callable('functionName'); 
is_callable([$foo, 'bar']);//$foo->bar() 
is_callable(['foo','bar']);//foo::bar() 
is_callable(function(){});//closure

php中 redis的subscribe订阅函数定义为

/**
 * Subscribe to a set of given channels for messages.
 * @param array|string  $channels
 * @param Closure  $callback
 * @return void
 */
public function subscribe($channels, Closure $callback)
{
  return $this->createSubscription($channels, $callback, __FUNCTION__);
}

项目中的应用

public function subscribeSellOrder(SellOrderProcess $sellOrderProcess)
{
  $closure = self::makeClosure($sellOrderProcess, 'sellOrdersProcess');
  $this->redis->subscribe(RtdataConst::SELL_CHANNEL_NAME, $closure);
}

protected static function makeClosure($obj, $method)
{
  return Closure::fromCallable([$obj, $method]);
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
xugege
讨论数量: 1

它们的不同之处:Closure 必须是匿名函数, callable 同时还可以为常规函数。

这么说是不准确的。

Callable 表示任何可以被调用的东西,除了普通函数,还有 ClassName::staticMethod / [$instance, "method"] 甚至是实现了 __invoke 魔术方法的类实例,都可以称作是 Callable。

至于 PHP 中的 Closure,可参见:博客:闭包匿名函数,还在傻傻搞不清楚吗?

4年前 评论
xugege (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!