Anonymous function: Difference between revisions

Content deleted Content added
PHP: Added a note about what create_function returns
PHP: Clarified proper use of variables in strings
Line 245:
[[PHP]] doesn't have true anonymous functions because the only way to reference functions is by name. The closest PHP is shown in the following.
<source lang="php">
$foo = create_function("'$x"', "'return $x*$x;"');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);
</source>
 
As of 5.2.5, the contents of $foo is a string of the form "\0lambda_X" where \0 is a null character (ASCII value zero) and X is a number starting with one.
 
It is important to note that the argument list and function body must be in single quotes or the dollar signs must be escaped.
Otherwise PHP will assume "$x" means the variable $x and will substitute it into the string (despite possibly not existing) instead of leaving "$x" in the string.
For functions with quotes or functions with lots of variables, it can get quite tedious to ensure the intended function body is what PHP interprets.
 
===Perl===