PHP 将匿名函数存储在数组中(class 上下文)

PHP store an anonymous function in an array (class context)

我知道可以将匿名函数作为数组值存储在 PHP 中,但为什么它在 class 上下文中 return NULL?

class firstClass {

    public static $functions = array();

    function __construct()
    {

        self::$functions += array( "echo" => function( $text ) { echo $text; }, "fruit" => "apple" );

    }

}

class secondClass {

    function __construct()
    {

        var_dump( firstClass::$functions ); // returns array(1){ ["fruit"] => string(5) => "apple" )
        var_dump( firstClass::$functions["echo"] ); // returns NULL

    }

}


$class = new firstClass;

firstClass 构造函数从不调用,您使用静态变量

有趣的是你得到的是 NULL — 当我测试你的代码时,我得到了预期的结果(即不是 NULL)。 试试下面的代码,也许这可行:(如果不行,试试升级你的 PHP 版本?)

// ----------------------------------------------------
// First try with a simple array, outside a class
// ----------------------------------------------------

$test_array = array(
    "string" => "some string" ,
    "function" => function() {
        echo 'i am an anonymous function outside a Class';
    }
);

var_dump($test_array);



// ----------------------------------------------------
// Now try in a Class context
// ----------------------------------------------------

class classContext {

    public static $functions = array();

    public function __construct() {
        self::$functions += array(
            "string" => "some string in classContext" ,
            "function" => function() {
                echo 'i am an anonymous function inside a Class';
            }
        );
    }

}

class secondClass {

    public function __construct() {
        var_dump(classContext::$functions);
        var_dump(classContext::$functions['function']);
    }
}

new classContext;
new secondClass;

结果应该是这样的:

array(2) {
    ["string"]=>
      string(11) "some string"

    ["function"]=>
      object(Closure)#1 (0) {}
}

array(2) {
    ["string"]=>
      string(27) "some string in classContext"

    ["function"]=>
      object(Closure)#3 (1) {
          ["this"]=> object(classContext)#2 (0) {}
      }
}

object(Closure)#3 (1) {
    ["this"]=> object(classContext)#2 (0) {}
}