Can we name an anonymous function without storing it in a variable in PHP?

In Javascript, it is easy to call a function returned by another function in a single declaration. Consider, for example:

function createOperation(operator)
{
    return Function("a", "b", "return a " + operator + "b;")
}

var result = createOperation("*")(2, 3);

Here we call a function to create another function that multiplies two values, and then calls this new function with two arguments.

If I try to reproduce a similar piece of code in PHP, I end up using two operators and one additional variable:

function createOperation(operator)
{
    return create_function('$a,$b', 'return $a '.$operator.' $b;');
}

$temp_var = createOperation("+");
$result = $temp_var(2, 3);

Short, Javascript form does not work:

$result = createOperation("+")(2, 3);

This is especially tedious when writing a chain of calls (pseudo-code):

foo(arg1)(arg2, arg3)()(...)

What will become:

$temp1 = foo($arg1);
$temp2 = $temp1($arg2, $arg3);
$temp3 = $temp2();
...

So my question is: is there a way in PHP to call a function returned by another function, without using temporary variables, or at least in the same expression?

+4

All Articles