PHP closures are very simple
Parent Feed:
Closures seem like big magic but in PHP they are just syntactic sugar over the following construct:
<?php
class OurClosure {
function __construct($add) {
$this->add = $add;
}
function __invoke($x) {
print $x + $this->add;
print "\n";
}
}
$print_add_2 = new OurClosure(2); // call __construct
$print_add_2(5); // when an object is called like a function it calls __invoke
?>
Now, closures use the following syntax:
<?php
function get_add_printer($add) {
return function ($x) use ($add) {
print $x + $add;
print "\n";
};
}
$print_add_2 = get_add_printer(2);
$print_add_2(5);
?>
This is the exact same -- it's internally implemented exactly like that:
function ($ARG1_TO_BE_USED_WHEN_CALLING_INVOKE, $ARG2_TO_BE_USED_WHEN_CALLING_INVOKE, ...) use ($ARG1_TO_STORE_IN_CONSTRUCT, $ARG2_TO_STORE_IN_CONSTRUCT, ...)
Original Post:
