'Can I put anonymous functions in arrays in PHP? [duplicate]
Possible Duplicate:
Workaround for basic syntax not being parsed
Why don't PHP attributes allow functions?
I'm getting
Parse error: syntax error, unexpected T_FUNCTION in /home/codemonkey/dev/broadnet/bito.api2/broadnet/resources/broadmapresource.php on line 87
From this code:
private $debugFunctions = array(
"testing" => function() // Line 87
{
return "I'm a test function!";
},
"foo" => function()
{
return "bar";
}
);
I was under the impression I could use anonymous PHP functions anywhere I could use $variables. Is this an exception, or am I doing something wrong?
I'm using PHP 5.3.9
Solution 1:[1]
Use a constructor:
class TestClass {
private $debugFunctions;
public function __construct() {
$this->debugFunctions = array(
"testing" => function()
{
return "I'm a test function!";
},
"foo" => function()
{
return "bar";
}
);
}
}
For explanation why, see xdazz's answer: class properties must be constant and known at compile time. If you need it to be dynamic or more complex, you cat populate it during initialization of the instance (in the constructor).
Solution 2:[2]
You can do that.
Just init it in the costructor:
function __construct() {
$debugFunctions = array(
"testing" => function() // Line 87
{
return "I'm a test function!";
},
"foo" => function()
{
return "bar";
}
);
}
Solution 3:[3]
Update: This answer was intended for PHP 5, it will not work with PHP 8.
Not like that, take a look at create_function. It creates a new function in the current scope and returns the function name.
private $debugFunctions = array(
"testing" => create_function('', 'return "I\'m a test function!";'),
"foo" => create_function('', 'return "bar";');
);
Not sure if the above example works, though. I didn't have time to test it.
Also note that using create_function can significantly slow down your application, depending on how frequent you use it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Czechnology |
| Solution 3 |
