PHP实际上是否支持lambdas?
<?php
class ExampleClass
{
public $variable = array(
"example" => function( $str )
{
return str_replace("a","-",$str);
}
);
}
?>
Run Code Online (Sandbox Code Playgroud)
错误:
解析错误:语法错误,第6行/var/www/test.php中的意外"函数"(T_FUNCTION)
我知道我可以使用create_function,但我讨厌它......
问题要简单得多 - 您无法使用复杂表达式初始化类属性.您可以将其设置为常量值,但不能将其设置为函数调用,函数创建等.
看这里:http://php.net/manual/en/language.oop5.properties.php
进一步说明 - 此代码无效,因为您尝试variable使用匿名函数初始化属性:
<?php
class ExampleClass
{
// fails because of complex expression
public $variable = array(
"example" => function($str) { return str_replace("a", "-", $str); }
);
}
Run Code Online (Sandbox Code Playgroud)
如果您希望该属性保存函数句柄,请按如下所示更改代码:
<?php
class ExampleClass
{
// might be left uninitialized as well
public $variable = null;
public function __construct()
{
// now object context is initialized
// so you can perform complex actions on it
$this->variable = array(
"example" => function($str) { return str_replace("a", "-", $str); }
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |