The main difference between the two is that closure is a class and a callable type.
callable type accepts anything that might be called :
var_dump( is_callable('functionName'), is_callable([$myClass, 'methodName']), is_callable(function(){}) );
In case closure will accept only an anonymous function. Note that in PHP version 7.1 you can convert functions to closures as follows: Closure::fromCallable('functionName') .
Example:
namespace foo{ class bar{ private $val = 10; function myCallable(callable $cb){$cb()} function myClosure(\Closure $cb){$cb()} // type hint must refer to global namespace } function func(){} $cb = function(){}; $fb = new bar; $fb->myCallable(function(){}); $fb->myCallable($cb); $fb->myCallable('func'); $fb->myClosure(function(){}); $fb->myClosure($cb); $fb->myClosure(\Closure::fromCallable('func')); $fb->myClosure('func');
So why use closure over callable ?
Strict because closure is an object that has some additional methods: call() , bind() and bindto() . They allow you to use a function declared outside the class and execute it as if it were inside the class.
$inject = function($i){return $this->val * $i;}; $cb1 = Closure::bind($inject, $fb); $cb2 = $inject->bindTo($fb); echo $cb1->call($fb, 2);
On the side note: the closure class cannot be extended as its final .
Xorifelse Dec 02 '16 at 23:09 2016-12-02 23:09
source share