8.8 Dynamically Creating Anonymous Functions


You want to create an anonymous (unnamed) function dynamically and then allow the user to access that function.

Technique

Use the create_function() function, which creates an anonymous function and returns its name :

 <?php function greet ($type) {     return create_function ('$greeting',                             "print \"$type: $greeting\";"); } $greeting1 = greet("Casual"); $greeting2 = greet("Formal"); $greeting1("How's it going?"); $greeting1("What's up doc?"); $greeting2("Hello"); $greeting2("Hello, my name is Sterling, it is a pleasure to meet you"); ?> 

Comments

The create_function() function will dynamically create a PHP function with arguments given by the first parameter and the code given by the second argument. It will return the function's unique name so that you can then call that function. This primitive form of closure can be used for many things, including smart callbacks.

Another use of the create_function() function is for the custom sort functions. Examine recipe 4.15 for more information. For further information about dynamically calling functions using variables , see the next recipe.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net