View Single Post
Old 06-30-2009, 04:44 PM   #8 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

Quote:
Originally Posted by Village Idiot View Post
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($patterncreate_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); 
Salathe is offline  
Reply With Quote