05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Anonymous Functions<br />

Some <strong>PHP</strong> functions use a function you provide them with to do part of their work.<br />

For example, the usort( ) function uses a function you create and pass to it as a<br />

parameter to determine the sort order of the items in an array.<br />

Although you can define a function for such purposes, as shown previously, these<br />

functions tend to be localized and temporary. To reflect the transient nature of the<br />

callback, create and use an anonymous function (or lambda function).<br />

You can create an anonymous function using create_function( ). This function takes<br />

two parameters—the first describes the parameters the anonymous function takes in,<br />

and the second is the actual code. A randomly generated name for the function is<br />

returned:<br />

$func_name = create_function(args_string, code_string);<br />

Example 3-7 shows an example using usort( ).<br />

Example 3-7. Anonymous functions<br />

$lambda = create_function('$a,$b', 'return(strlen($a) - strlen($b));');<br />

$array = array('really long string here, boy', 'this', 'middling length', 'larger');<br />

usort($array, $lambda);<br />

print_r($array);<br />

The array is sorted by usort( ), using the anonymous function, in order of string<br />

length.<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Anonymous Functions | 71

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!