Monday, 22 February 2010

PHP now supports anonymous functions

Did you know PHP 5.3 now supports anonymous functions? Let's look at some code.

This is the old way how you used to do it:

<?php
//the array we're working with
$arr = array(1,2,3,4,5);

//declare a function for use as callback
function callback($i){
    echo $i;
}

//use the callback
array_walk($arr, 'callback'); //outputs 12345
?>

Now, this is the new way:

<?php
$arr = array(1,2,3,4,5);

//use anonymous callback method
array_walk($arr, function($i){echo $i;}); //outputs 12345

?>

And here's another interesting thing you can now do with PHP:

<?php
$arr = array(5,4,3,2,1);

//create a variable which will be a reference to a new function later
$fn = null;

//$fn's function is declared within the arguments of another function
array_walk($arr, $fn = function($i){echo $i;}); //outputs 54321

//calls the new function in $fn
$fn(68); //outputs 68
?>

Did you know you could use external variables inside of closures? You need the use keyword and pass the variables into it separated by commas like so:

$basePath = "/usr/home/";
$getPathFor = function($name) use ($basePath) {return "$basePath$name";}
echo $getPathFor("bob"); // /usr/home/bob

Nice.

No comments:

Post a Comment