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

时间:2017-05-29 13:07:27

标签: php arrays function class anonymous

我知道可以在PHP中将匿名函数存储为数组值,但为什么它会在类上下文中返回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;

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

很有趣的是你得到了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) {}
}