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 协议》,转载必须注明作者和本文链接
推荐文章: