Daniel Nill
Daniel Nill

Reputation: 5747

PHP closures require arguments passed

Trying to figure out why php anonymous functions only work when they are given parameters in the function header.

For example

$f = function(){
    echo "hello world";
};
$f;
$f();

won't work. But

$f = function($argument){
    echo $argument;
}
$f('hello world');

works just fine.

Why does it need arguments and is there any work around for this?

EDIT

This must be a version issue. I'm on 5.3.18 and my first example definitely doesn't work. For those not believing, it throws:

Parse error: syntax error, unexpected T_FUNCTION in index.php(192) : 
  eval()'d code on line 1

EDIT

After looking at DaveRandom's answer I'm back to having no idea what's happening. That is if they are correct that it works in 5.3.10 ...

Upvotes: 0

Views: 171

Answers (3)

nickb
nickb

Reputation: 59699

This is perfectly valid syntax and outputs hello world:

$f = function(){
    echo "hello world";
};
$f();

The line $f; does nothing, and would be equivalent to declaring any other variable and then writing that new variable name and a semicolon.

Anonymous functions do not require parameters, see the manual for more details about them.

You are getting those syntax errors because you are running a PHP version < 5.3.

Upvotes: 5

DaveRandom
DaveRandom

Reputation: 88647

The first code works fine if you remove the meaningless $f; line.

Edit Actually, it still works even if you leave that line in. And in 5.3.10 as well.

Upvotes: 3

mario
mario

Reputation: 145482

This doesn't invoke the closure:

$f;

But this one does:

$f();

Function calls require parens to be recognized by the parser. If you just mention the variable $f; then that's an empty expression. The closure object contained in $f gets assigned to a temporary zval (variable placeholder), then thrown away.

Upvotes: 4

Related Questions