我正在尝试实现我自己的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。关于这个,你能把一个函数存储在PHP数组中吗?
必须在构造函数或其他方法中定义方法,而不是直接在类成员声明中定义。
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;
};
}
}