我正在尝试实现我自己的MVC框架,并发明了一种非常好的方法来提供虚拟字段和其他关系的定义。
根据其他一些关于堆栈溢出的高投票率帖子,这实际上应该是可行的:
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。我做错了什么?
发布于 2013-06-25 17:23:11
必须在构造函数或其他方法中定义方法,而不是直接在类成员声明中定义。
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;
};
}
}https://stackoverflow.com/questions/17303558
复制相似问题