TechniqueUse 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"); ?> CommentsThe 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. |