函数数组作为对象的私有属性

时间:2013-11-12 06:42:59

标签: php oop anonymous-function

我想知道这个php代码中出现“意外的T_FUNCTION”错误的原因:

class T
{
    private $array_of_functions = array(
        '0' => function() { return true; }
    );
}

1 个答案:

答案 0 :(得分:2)

您不能将此类构造用作默认属性值。默认property value只能是常量表达式 - 因此它不能包含闭包定义,因为它是动态的(即在运行时构造时进行评估)。相反,你应该在类构造函数中初始化它:

class T
{
   private $array_of_functions = [];

   public function __construct()
   {
      $this->array_of_functions = [
         function() { return true; }
      ];
   }
}