A closure or callback function is a new feature as of PHP 5.3. Closures makes it easy to create recursive code and small functions that does not need to be in the global scope.
<?php $closure = funciton($what){
echo "Hello {$what}!";
}
// Runs the function like any other function but with dollar ($) sign infront to call to the variable.
$closure('World');
??>
Sometimes you would want to access global variables outside of the function itself, its accomplished using the use statement.
<?php $what = 'World';
$closure = funciton() use ($what){
echo "Hello {$what}!";
}
$closure();
??>
Sometimes you want to pass the function to another function or class method. This is the correct way:
<?php function test($closure){
// Check if the variable is a closure.
if (is_callable($closure)){
$number = $closure();
}
}
$closure = function(){
return 1;
};
test($closure);
??>
Test2
Comment by Anonymous on 22nd October 2011, 6:50 PM Comment this post
Test