我可以在 PHP 中将匿名函数放入数组中吗?
我得到了
解析错误:语法错误,第 87 行 /home/codemonkey/dev/broadnet/bito.api2/broadnet/resources/broadmapresource.php 中出现意外的 T_FUNCTION
从这段代码中:
private $debugFunctions = array(
"testing" => function() // Line 87
{
return "I'm a test function!";
},
"foo" => function()
{
return "bar";
}
);
我的印象是我可以在任何可以使用匿名 PHP 函数的地方使用$variables
。这是例外,还是我做错了什么?
我正在使用 PHP 5.3.9
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能对类属性执行此操作,属性初始化必须是常量值。
You can't do this with the class property, the property initialization must be a constant value.
使用构造函数:
有关原因的解释,请参阅xdazz 的回答:类属性必须是常量且在编译时已知。如果您需要它是动态的或更复杂的,您可以在实例初始化期间(在构造函数中)填充它。
Use a constructor:
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).
更新:这个答案适用于 PHP 5,它不适用于 PHP 8。
不是这样的,请查看 创建函数。
它在当前作用域中创建一个新函数并返回函数名称。
但不确定上面的例子是否有效。我没有时间测试它。
另请注意,使用 create_function 可能会显着降低应用程序的速度,具体取决于您使用它的频率。
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.
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.
你可以这么做。
只需在构造函数中初始化它:
You can do that.
Just init it in the costructor: