Bra*_*rad 1 php oop inheritance magic-methods
其他语言的一个便利功能是能够为属性创建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);
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我的计划是扩展这个类get_someproperty()并set_someproperty()在这个扩展类中定义适当的.
<?php
class SomeNewClass extends ObjectWithGetSetProperties {
protected $_someproperty;
public function get_someproperty() {
return $this->_someproperty;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
麻烦的是,基类ObjectWithGetSetProperties是无法看到我的方法get_someproperty()在SomeNewClass.我总是得到错误,"密钥不可用".
有没有办法解决这个问题,允许基类ObjectWithGetSetProperties工作,还是我必须在每个类中创建那些__get()和__set()魔术方法?
试试吧is_callable.示例代码片段:
<?php
date_default_timezone_set("America/Edmonton");
class A {
protected $_two="goodbye";
protected $_three="bye";
protected $_four="adios";
public function __get($name) {
if (is_callable(array($this,$m="get_$name"))) {
return $this->$m();
}
trigger_error("Doh $name not found.");
}
public function get_two() {
return $this->_two;
}
}
class B extends A {
protected $_one="hello";
protected $_two="hi";
protected $_three="hola";
public function get_one() {
return $this->_one;
}
public function get_two() {
return $this->_two;
}
public function get_three() {
return $this->_three;
}
public function get_four() {
return $this->_four;
}
}
$a=new a();
echo $a->one."<br />";//Doh one not found.
echo $a->two."<br />";//goodbye
echo $a->three."<br />";//Doh three not found.
echo $a->four."<br />";//Doh four not found.
$b=new b();
echo $b->one."<br />";//hello
echo $b->two."<br />";//hi
echo $b->three."<br />";//hola
echo $b->four."<br />";//adios
?>
Run Code Online (Sandbox Code Playgroud)
(更新以显示B覆盖的位置A)