使用PHP,我如何定义/声明getter和setter方法/函数作为类中属性声明的一部分?
我想做的是指定getter和setter方法作为属性的一部分,而不是声明单独的set_propertyName($value)
和get_propertyName()
函数/方法。
我得到了什么:
class my_entity {
protected $is_new;
protected $eid; // entity ID for an existing entity
public function __construct($is_new = FALSE, $eid = 0) {
$this->is_new = $is_new;
if ($eid > 0) {
$this->set_eid($eid);
}
}
// setter method
public function set_eid($eid) {
$is_set = FALSE;
if (is_numeric($eid)) {
$this->eid = intval($eid);
$is_set = TRUE;
}
return $is_set;
}
}
我想要的(不让$this->eid成为对象):
class my_entity {
protected $is_new;
// entity ID for an existing entity
protected $eid {
set: function($value) {
$is_set = FALSE;
if (is_numeric($value)) {
$this->eid = intval($value);
$is_set = TRUE;
}
return $is_set;
}, // end setter
};
public function __construct($is_new = FALSE, $eid = 0) {
$this->is_new = $is_new;
if ($eid > 0) {
$this->set_eid($eid);
}
}
// setter method/function removed
}
PHP每个类只允许一个getter和一个setter函数,它们是__get
&__set
魔法方法。这两个神奇的方法必须处理所有私有/不可访问属性的get和set请求。http://www.php.net/manual/en/language.oop5.magic.php
private function set_eid($id)
{
//set it...
$this->eid = $id;
}
private function get_eid($id)
{
//return it...
return $this->eid;
}
public function __set($name, $value)
{
switch($name)
{
case 'eid':
$this->set_eid($value);
break;
}
}
public function __get($name)
{
switch($name)
{
case 'eid':
return $this->get_eid();
break;
}
}
在2 switch语句中,您还可以添加其他属性的名称。
重要的是要记住,__get
和__set
只有在变量不可访问时才会被调用,这意味着当从类内部获取或设置时,您仍然必须手动调用set__eid
。
这是在PHP 5.5中提出的,但投票未能获得必要的2/3多数来接受它进入核心,所以它不会被实现(尽管实现该更改的代码已经提交)。
完全有可能(随着大量新的PHP引擎和Hacklang的出现),它将在未来的时间重新提交,特别是如果Hacklang决定实现它;但是目前在PHP