Recipe 6.12. Creating Dynamic Functions


6.12.1. Problem

You want to create and define a function as your program is running.

6.12.2. Solution

Use create_function( ):

$add = create_function('$i,$j', 'return $i+$j;'); $add(1, 1); // returns 2

6.12.3. Discussion

The first parameter to create_function( ) is a string that contains the arguments for the function, and the second is the function body. Using create_function( ) is exceptionally slow, so if you can predefine the function, it's best to do so.

The most frequently used case of create_function( ) in action is to create custom sorting functions for usort( ) or array_walk( ):

// sort files in reverse natural order usort($files, create_function('$a, $b', 'return strnatcmp($b, $a);'));

6.12.4. See Also

Recipe 4.17 for information on usort( ); documentation on create_function( ) at http://www.php.net/create-function and on usort( ) at http://www.php.net/usort .




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

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