06-30-2009, 04:44 PM
|
#8 (permalink)
|
|
Moderateur
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
|
Quote:
Originally Posted by Village Idiot
I don't see the point in anonymous functions. Could someone enlighten me to how they are an improvement?
|
I can't think of a situation where an anonymous function would be required which cannot be done any other way, so it'll certainly be possibly to continue life without ever using an anonymous PHP function.
However, I see the three following scripts and prefer the new anonymous function one. It's a silly example script but I think it gets the point across.
PHP Code:
$subject = 'Hello, world!';
$pattern = '/\bworld\b/i';
$replacement = 'Salathe';
/*
Regular, boring function
*/
function mycallback($match)
{
// Do some complicated stuff
return $GLOBALS['replacement'];
}
echo preg_replace_callback($pattern, 'mycallback', $subject);
/*
Anonymous function via create_function
*/
echo preg_replace_callback($pattern, create_function('$match', '
// Do some complicated stuff
return $GLOBALS["replacement"];
'), $subject);
/*
Anonymous function
*/
$callback = function($match) use ($replacement)
{
// Do some complicated stuff
return $replacement;
};
echo preg_replace_callback($pattern, $callback, $subject);
|
|
|
|