PHP class 中的函数字面量

Function literal in PHP class

请看一下这段代码:

$array = array(
    'action' => function () { echo "this works"; }
);

class Test {
    public $array = array(
        "action" => function () { echo "this doesn't"; }
    );
}

第一个函数文字解析正常,但第二个 - class 内的那个 - 触发语法错误:

Parse error: syntax error, unexpected 'function' (T_FUNCTION)...

有人可以给我解释一下吗?这是一个错误吗?

编辑:这是最新的 PHP:5.6.6

来自 class 它是 属性 !

来自属性的规则:

Declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

http://php.net/manual/en/language.oop5.properties.php

像这样尝试一下,让我知道这是否适合你

<?php
$array = array('action' => function () { echo "this works"; });
class Test {
    public $arr;
    function __construct() {
        $this->arr = array("action" => function () { echo "this works too"; });
    }
    function getArr(){
        var_dump($this->arr);
    }
}

var_dump($array);
$obj = new Test();
$obj->getArr();

我没有机会在 PHP 5.6.6 上测试您的代码,但我认为这段代码可以解决您的问题。

class Test{

    public $array;

    function __construct(){

            $this -> array = array(

                'action'    =>  function (){

                    echo 'It works too';
                }
            );
    }
}

$test = new Test();
$test -> array['action']();