[ Team LiB ] Previous Section Next Section

Creating Anonymous Functions

You can 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; it 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 our function body.

In Listing 6.15, we create a simple anonymous function to add two numbers together.

Listing 6.15 A Simple Anonymous Function
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 6.15</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $my_anon = create_function( '$a, $b', 'return $a+$b;' );
12: print $my_anon( 3, 9 );
14: // prints 12
15: ?>
16: </div>
17: </body>
18: </html>

Note that we used single quotation marks when passing arguments to create_function(). That saved us from having to escape the variable names within the arguments. We could have used double quotation marks, but the function call would have been a little more involved:

$my_anon = create_function( "\$a, \$b", "return \$a+\$b;" );

So, what use are anonymous functions? In practical terms you will probably use them only when built-in functions need to be passed callback functions. A callback function is generally written by the user and designed to be invoked (usually repeatedly) by the function to which it is passed. You will see examples of this in Hour 16, "Working with Dates and Times."


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.

    [ Team LiB ] Previous Section Next Section