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 …
This is perfectly valid syntax and outputs
hello world: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.