Created
June 13, 2019 15:17
-
-
Save bosunski/4409ed9a955b9329292ebe597e9b3bde to your computer and use it in GitHub Desktop.
A brief explannation of Callables and Closures.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// An Anonymous Class or Normal Classes | |
$class = new class { | |
public function method() { | |
echo 'In a Class!', PHP_EOL; | |
} | |
}; | |
// We can write this ... π€ | |
$arrayLikeCallable = [new $class, 'method']; | |
/** | |
* An array of 2 Elements whose 1st element is an object | |
* and the second element is a public method that exists in that object ... is a Callable π€ | |
*/ | |
var_dump(is_callable($arrayLikeCallable)); // TRUE | |
// ... But it's not a Closure π₯Ά | |
var_dump($arrayLikeCallable instanceof Closure); // FALSE | |
// We can Convert Array based Callable to Closure Like this π | |
$closure = Closure::fromCallable($arrayLikeCallable); | |
// Then it becomes a closure π€β | |
var_dump( $closure instanceof Closure); // TRUE | |
// This is an Anonymous function π | |
$function = function() { | |
echo 'In a Function!', PHP_EOL; | |
}; | |
// An Anonymous function is callable | |
var_dump(is_callable($function)); // TRUE | |
// An Anon function is also a Closure at the same time π | |
var_dump($function instanceof Closure); // TRUE | |
$class = new class { | |
public function method() { | |
echo 'In a Class!', PHP_EOL; | |
} | |
}; | |
$function = function() { | |
echo 'In a Function!', PHP_EOL; | |
}; | |
function callCallable(callable $callable) { | |
call_user_func($callable); | |
} | |
$arrayLikeCallable = [new $class, 'method']; | |
callCallable($arrayLikeCallable); | |
callCallable($function); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment