尝试创建匿名函数数组时出现语法错误

时间:2013-06-25 17:18:15

标签: php anonymous-function

我正在尝试实现自己的MVC框架,并发明了一种非常好的方法来提供虚拟字段和其他关系的定义。

根据stackoverflow上的一些其他高投票帖子,这实际上应该有效:

class User extends Model {

  public $hasOne = array('UserSetting');

  public $validate = array();

  public $virtualFields = array(
      'fullname' => function () {
          return $this->fname . ($this->mname ? ' ' . $this->mname : '') . ' ' . $this->lname;
      },
      'official_fullname' => function () {

      }
  );
}

但它不起作用。它说:解析错误:语法错误,意外T_FUNCTION 。我做错了什么?

PS。谈论这个Can you store a function in a PHP array?

1 个答案:

答案 0 :(得分:3)

您必须在构造函数或其他方法中定义方法,而不是直接在类成员声明中定义。

class User extends Model {

  public $hasOne = array('UserSetting');

  public $validate = array();

  public $virtualFields = array();

  public function __construct() {
     $this->virtualFields = array(
        'fullname' => function () {
            return $this->fname . ($this->mname ? ' ' . $this->mname : '') . ' ' . $this->lname;
        },
        'official_fullname' => function () {

        }
    );
  }
}

虽然可行,但PHP的魔术方法__get()更适合这项任务:

class User extends Model {

  public $hasOne = array('UserSetting');

  public $validate = array();

  public function __get($key) {
     switch ($key) {
       case 'fullname':
           return $this->fname . ($this->mname ? ' ' . $this->mname : '') . ' ' . $this->lname;
       break;

       case 'official_fullname':
         return '';
       break;
    };
  }
}
相关问题