Anonymous functions in PHP – What, Why, How ?

Anonymous functions immediately remind us of  ”Closure” in Javascript.  And that’s exactly what PHP supports.  For Javascript, we can not do without closures. However, for PHP it is less common use compared to Javascript. Let’s dig it !

To formally define it — Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Anonymous functions have been available in PHP for a long time: create_function has been around since PHP 4.0.1. However you’re quite right that there is a new concept and syntax available as of PHP 5.3.

Very useful feature

  • If you are using function just once, no advantage defining it seeprately
  • Many often, function is accepted as callback parameter and  Anonymous function is best way to go !
  • Can be defined as  value of variable. Very handy in many situation.

Examples

Variable Initializing

<?php

$greet = function($name)
{
printf(“Hello %s\r\n”, $name);
};
$greet(‘World’);
$greet(‘PHP’);
?>

Callback Parameter

<?php
echo preg_replace_callback(‘~-([a-z])~’, function ($match) {
return strtoupper($match[1]);
}, ‘hello-world’);
// outputs helloWorld
?>

If you have not used Anonymous functions ( i.e Closure )  before, try them out.  You will surley find them handy.


Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*

Find us on Facebook

?