Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

PHP is awesome

Name: Anonymous 2007-08-28 17:56 ID:xY3vpdBA

This is how you create a anonymous function in PHP:

$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');


Name: Anonymous 2007-08-29 5:32 ID:dqo1AGje

PHP's create_function and 1.5-class functions (variable functions, e.g. $a = 'strlen'; $a($b)) as well as array_map and company can make your life easier if you have to work with PHP. The syntax for create_function, or lack of, requires quote hell though, and you have no nested scoping, so all you're getting are anonymous functions. At most, you can create an inefficient read-only closure if you var_export() your outer variables into the anonymous function's code.

However, there's a problem with create_function: PHP doesn't really have anon functions, they are all namefags, and they are returned as functions with an invalid character in their name. They work for $a = create_function(...); $a($b); but they won't work if you try to use one inside another, e.g. $a = create_function(...); $b = create_function(..., "... $a($c) ...");. In order to fix this, and to simplify the creation of simple no-statement anon functions, I've created this more Pythonic function I use to spare myself of some pain:

function lambda($param, $expr) {
    static $number = -1;
    $number++;
    $name = '___lambda' . $number;
    eval("function $name($param) {return $expr;}");
    return $name;
}


(Note that, although this uses eval, it's not any less safe than create_function.)

Example:
$arr1 = array(1, 2, 3, 4, 5);
$arr2 = array_map(lambda('$x', '$x + 1'), $arr1);

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List