Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bosunski
Created June 13, 2019 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bosunski/4409ed9a955b9329292ebe597e9b3bde to your computer and use it in GitHub Desktop.
Save bosunski/4409ed9a955b9329292ebe597e9b3bde to your computer and use it in GitHub Desktop.
A brief explannation of Callables and Closures.
<?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