A quick introduction to PHP anonymous functions

If you haven’t used the anonymous functions introduced in PHP 5.3 you are missing out on a powerful tool. In this simple example we are given an array of names to display. But some of the names are not capitalized correctly. We will use our first anonymous function as a callback to correct this mistake. Then we will use another anonymous function to prepare the names to be displayed.

<?php
//anonymousfunc.php
$names = array('jeff','Mary ann','John paul','Marie');

array_walk($names,function(&$value){
o$name_parts = explode(' ',$value);
oforeach($name_parts as &$part){
o$part = ucfirst($part);
o}
o$value = implode(' ',$name_parts);
});

foreach($names as $name){
o$add_break = function($line){
oreturn $line.'<br>';
o};
oecho $add_break($name);
}

Capture

Our first anonymous function begins on line 5. array_walk() will give us the value of the array as the first parameter, and we take it by reference. Then we break the value up into its constituent parts around any spaces that may be in the name. After we capitalize each part we then set the $value with the new full name.

The second anonymous function is a bit of a contrived example, but it is meant to show that an anonymous function doesn’t need to be a callback. On line 14 we begin defining the function which will simply return whatever text it is given with a line break afterwards. Notice how this type of function is called on line 17.

So why does this matter? The short answer is structure. I could have fixed the capitalization with a double nested foreach loop but this solution is arguably more elegant. It is also tempting to create a function for this and then call it from anywhere. In this situation we need this function and we may never need it again in a larger system, so it makes sense to create it here where it will be used.

If this is the first time you are hearing about anonymous functions I would encourage you to try to use them in your next PHP script to get a better feel for how they work.

Leave a Reply

Your email address will not be published. Required fields are marked *