PHP 5.3+不支持lambdas?

Jor*_*sen -2 php lambda class

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,但我讨厌它......

Tom*_*zyk 5

问题要简单得多 - 您无法使用复杂表达式初始化类属性.您可以将其设置为常量值,但不能将其设置为函数调用,函数创建等.

看这里: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)

  • @OlafErlandsen我同意很烦人,你想要的东西不起作用,它的原因多种多样,它们都与PHP内部工作方式有关,而对它们的全面讨论实际上超出了StackOverflow的范围.理论上可以实现有限数量的你想要的东西(特别是,'use()`是不可能的,主要是因为它没有任何意义),但它不太可能在不久的将来发生. (2认同)