dongwu3747 2013-11-12 06:42
浏览 47
已采纳

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

I would like to know the reason of "Unexpected T_FUNCTION" error in this php code:

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

1条回答 默认 最新

  • down_load1117 2013-11-12 06:48
    关注

    You can not use such construction as default property value. Default property value can be only constant expression - so it can not contain closure definition since it's dynamic (i.e. evaluated when constructed at runtime). Instead you should initialize it inside class constructor:

    class T
    {
       private $array_of_functions = [];
    
       public function __construct()
       {
          $this->array_of_functions = [
             function() { return true; }
          ];
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?