Reputation: 47791
In Javascript, it's easy to call a function returned by another function in one single statement. 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, then call this new function with two arguments.
If I try to replicate a similar code snippet in PHP, I end up using two statements and one extra variable:
function createOperation(operator)
{
return create_function('$a,$b', 'return $a '.$operator.' $b;');
}
$temp_var = createOperation("+");
$result = $temp_var(2, 3);
The short, Javascript-like form doesn't work:
$result = createOperation("+")(2, 3);
This is especially tedious when writing an invocation chain (pseudocode):
foo(arg1)(arg2, arg3)()(...)
Which would 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 one single same statement?
Upvotes: 4
Views: 113
Reputation: 215009
As seen in php repo, @NikiC is actively working on implementing his RFC, the ()()
syntax is already in the trunk:
https://github.com/php/php-src/commit/64e4c9eff16b082f87e94fc02ec620b85124197d
I don't know what the release map looks like, hope we'll get decent syntax in php very soon.
Upvotes: 1