Share
Share
 

Anonymous Functions and Closure in PHP

By Chris London

It’s about time that PHP joined the band wagon of anonymous functions. Anonymous functions, also known as closures, are functions with no specified name. These functions are stored in variables and can be passed around. Anonymous functions have been in other programming languages like Javascript, so if you know Javascript then anonymous functions are nothing new.

Anonymous functions have only been introduced into PHP as of version 5.3.0. So if you are running an older version of PHP you will not be able to do anonymous functions.

Anonymous Function as a Callback

function stringEdit($string, $callback) {
     return $callback($string);
}
 
echo stringEdit("hello world", function ($string) {
          return ucwords($string);
     });
// Outputs "Hello World";

As you can see here when I call the function stringEdit I pass a function as the parameter for $callback. Pretty cool, huh?! This opens endless possibilities.

Anonymous Function Assigned to a String

$my_callback = function ($string) {
          return ucwords($string);
     }; // Don't forget the semi-colon
 
echo $my_callback("hello world");
// Outputs "Hello World";

This example shows how to store functions into a variable and then use them. This example also outputs “Hello World”.

Real-World Example of Anonymous Functions

There are many times in my programming career where I’ve had to display a table of data to the user from a MySQL database. I find the code to do such a thing to be tedious and cumbersome. There is usually a lot of repetitive code if you’re not careful. For example, if you have a page that displays the user data and a page that displays payment history a lot of the time the programmer will make the user data page and then make a new copy of the file for the payment history and just rename the fields. Here is an example that uses anonymous functions as callbacks to format the data. The code is well documented to help understand what the code is doing.

// This function uses ucwords which
// uppercases the first letter of
// each word
$upperCase = function($string) {
     return ucwords($string);
};
 
// This function uses the statusID
// to determine the appropriate
// status. This usually is done
// through a mysql join
$statusCode = function($statusID) {
     switch ($statusID) {
          case '0':
               return 'Disabled';
          case '1':
               return 'Active';
          case '2':
               return 'Suspended';
          default:
               return 'Unknown';
     }
};
 
// This is our config array. It has
// the column name (column), the
// display title for the column (title)
// and an optional callback.
$config = array(
     // This column doesn't have a callback
     array(
          'column'=>'id',
          'title'=>'Id'
     ),
     // This column uses the upper-
     // case callback.
     array(
          'column'=>'name',
          'title'=>'Name',
          'callback'=>$upperCase
     ),
     // This column uses the statusCode
     // callback.
     array(
          'column'=>'status',
          'title'=>'Status',
          'callback'=>$statusCode
     )
);
 
// Getting only relevant data from MySQL
$query = "SELECT id, name, status FROM users";
$results = mysql_query($query);
 
// Here we begin displaying the table. I recommend
// you use an MVC style of programming meaning you
// seperate your PHP from your HTML but that
// is beyond the scope of this tutorial
echo '<table>';
 
// This displays the title row using the config
// table's title columns
echo '<tr>';
foreach ($config as $val) {
     echo '<th>' . $val['title']. '</th>';
}
echo '</tr>';
 
// We loop through the data we received from the
// MySQL database
while ($row = mysql_fetch_assoc($results)) {
     echo '<tr>';
     // For each row we need to cycle through each column
     foreach ($config as $val) {
          echo '<td>';
          if (isset($val['callback'])) {
               // If the column has a callback then run the
               // data through the callback
               echo $val['callback'](
                    $row[$val['column']]
               );
          } else {
               // If no callback then just display the data
               // straight
               echo $row[$val['column']];
          }
          echo '</td>';
     }
     echo '</tr>';
}
echo '</table>';

The data in the MySQL database

array(
     array('id'=>1, 'name'=>'chris London', 'status'=>1),
     array('id'=>2, 'name'=>'KC London', 'status'=>2),
     array('id'=>3, 'name'=>'Douglas london', 'status'=>0)
);

Result:

Id Name Status
1 Chris London Active
2 KC London Suspended
3 Douglas London Disabled

 

That’s a lot to digest. I hope it was understandable. If I wasn’t clear on anything please let me know. I’ll answer all legitimate questions posted in the comments.

Tags: , , ,

This entry was posted on Tuesday, April 20th, 2010 at 2:52 pm and is filed under Programming, Tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Anonymous Functions and Closure in PHP”

  1. I benchmarked the anonymous functions. Here’s what I discovered: bit.ly/bAjA6k

  2. WP Themes says:

    Nice post and this mail helped me alot in my college assignement. Thank you for your information.

Leave a Reply