So I\'m programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I
PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The RFC for closures give a good example:
function replace_spaces ($text) {
$replacement = function ($matches) {
return str_replace ($matches[1], ' ', ' ').' ';
};
return preg_replace_callback ('/( +) /', $replacement, $text);
}
This lets you define the replacement
function locally inside replace_spaces()
, so that it's not:
1) Cluttering up the global namespace
2) Making people three years down the line wonder why there's a function defined globally that's only used inside one other function
It keeps things organized. Notice how the function itself has no name, it simply is defined and assigned as a reference to $replacement
.
But remember, you have to wait for PHP 5.3 :)
You can also access variables outside it's scope into a closure using the keyword use
. Consider this example.
// Set a multiplier
$multiplier = 3;
// Create a list of numbers
$numbers = array(1,2,3,4);
// Use array_walk to iterate
// through the list and multiply
array_walk($numbers, function($number) use($multiplier){
echo $number * $multiplier;
});
An excellent explanation is given here What are php lambdas and closures