其他语言的便利功能之一是能够为属性创建 get 和 set 方法。在试图找到一种在 PHP 中复制此功能的好方法时,我偶然发现了这个: http ://www.php.net/manual/en/language.oop5.magic.php#98442
这是我对该课程的细分:
<?php
class ObjectWithGetSetProperties {
public function __get($varName) {
if (method_exists($this,$MethodName='get_'.$varName)) {
return $this->$MethodName();
} else {
trigger_error($varName.' is not avaliable .',E_USER_ERROR);
}
}
public function __set($varName,$value) {
if (method_exists($this,$MethodName='set_'.$varName)) {
return $this->$MethodName($value);
} else {
trigger_error($varName.' is not avaliable .',E_USER_ERROR);
}
}
}
?>
我的计划是扩展这个类并在这个扩展类中定义适当的get_someproperty()
和set_someproperty()
。
<?php
class SomeNewClass extends ObjectWithGetSetProperties {
protected $_someproperty;
public function get_someproperty() {
return $this->_someproperty;
}
}
?>
问题是, 的基类ObjectWithGetSetProperties
无法get_someproperty()
在SomeNewClass
. 我总是收到错误消息,“密钥不可用”。
有什么办法可以解决这个问题,允许基类ObjectWithGetSetProperties
工作,还是我必须在每个类中创建这些__get()
和__set()
魔术方法?