Anonymous functions (closures) in PHP >= 5.3
According to the PHP documentation, anonymous functions, or closures, allow the creation of functions that haven’t got a specified name.
Simple example:
$greeting = function($name) { printf("Hello %s\r\n", $name); }; $greeting('World'); |
But in this example we’ll go a little further.
Imagine you have this array:
$users = array( array('id' => 1, 'name' => 'Steve', 'birthday' => '1984-02-17'), array('id' => 2, 'name' => 'Bill', 'birthday' => '1985-07-07'), array('id' => 3, 'name' => 'James', 'birthday' => '1974-11-17') ); |
If we want to get the ids for each user, we would do something like this:
$ids = array(); foreach ($users as $user) { $ids[] = $user['id']; } |
But there is a much more elegant way to do this using anonymous functions (closures):
$ids = array_map(function ($user) { return $user['id']; }, $users); |
Much cleaner and elegant… Now we want to get the users who were born after 1980. Normally do this:
$filtered_users = array(); $start_date = strtotime('1980-01-01'); foreach ($users as $user) { if (strtotime($user['birthday']) >= $start_date) { $filtered_users[] = $user; } } |
Now we will use again anonymous functions or closures:
$start_date = strtotime('1980-01-01'); $filtered_users = array_filter($users, function($user) { global $start_date; return strtotime($user['birthday']) >= $start_date; }); |
These are just a few examples of anonymous functions or closures in PHP.
0 Comments