It is possible to create functions on the fly during script execution. Because such functions are not themselves given a name, but are stored in variables or passed to other functions, they are known as anonymous functions. PHP provides the create_function() function for creating anonymous functions. create_function() requires two string arguments. The first argument should contain a comma-delimited list of argument variables, exactly the same as the argument variables you would include in a standard function declaration. The second argument should contain the function body.
Listing 6.15 creates a simple anonymous function to add two numbers together.
1: <html> 2: <head> 3: <title>Listing 6.15</title> 4: </head> 5: <body> 6: <?php 7: $my_anon = create_function( '$a, $b', 'return $a+$b;' ); 8: print $my_anon( 3, 9 ); 9: // prints 12 10: ?> 11: </body> 12: </html>
As of this writing, the use of anonymous functions will cause a segmentation fault when running the Zend Optimizer. |
Put these lines into a text file called anon.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:
12
Note that we use single quotes when passing arguments to create_function(). That saves us from having to escape the variable names within the arguments. We could have used double quotes, but the function call would have been a little more involved:
$my_anon = create_function("\$a, \$b", "return \$a+\$b;");
So what is the use of anonymous functions? In practical terms, you will probably only use them when you need to pass callback functions to built-in functions. A callback function is generally written by the user and is designed to be invoked (usually repeatedly) by the function to which it is passed.
The second argument to create_function() is the function body. Don't forget to end the last statement in this string with a semicolon. The interpreter will complain and your anonymous function will not be executed if you omit it. |