PHP Magic Methods __set和__get
发布时间:2020-12-13 22:07:54 所属栏目:PHP教程 来源:网络整理
导读:这样做会被认为是好的做法…… 我有A类,其定义如下: class A{ private $_varOne; private $_varTwo; private $_varThree; public $varOne; public function __get($name){ $fn_name = 'get' . $name; if (method_exists($this,$fn_name)){ return $this-$fn
|
这样做会被认为是好的做法……
我有A类,其定义如下: class A{
private $_varOne;
private $_varTwo;
private $_varThree;
public $varOne;
public function __get($name){
$fn_name = 'get' . $name;
if (method_exists($this,$fn_name)){
return $this->$fn_name();
}else if(property_exists('DB',$name)){
return $this->$name;
}else{
return null;
}
}
public function __set($name,$value){
$fn_name = 'set' . $name;
if(method_exists($this,$fn_name)){
$this->$fn_name($value);
}else if(property_exists($this->__get("Classname"),$name)){
$this->$name = $value;
}else{
return null;
}
}
public function get_varOne(){
return $this->_varOne . "+";
}
}
$A = new A();
$A->_varOne; //For some reason I need _varOne to be returned appended with a +
$A->_varTwo; //I just need the value of _varTwo
为了不创建4个set和4个get方法,我使用了魔术方法来为我需要的属性调用受尊重的getter,或者只是返回属性的值而不做任何改变.这可以考虑这个好习惯吗? 解决方法
不了解最佳实践,但是当您需要延迟加载属性时__get非常有用,例如获取它时涉及复杂的钙化或数据库查询.此外,php提供了一种优雅的方法来缓存响应,只需创建一个具有相同名称的对象字段,这样可以防止再次调用getter.
class LazyLoader
{
public $pub = 123;
function __get($p) {
$fn = "get_$p";
return method_exists($this,$fn) ?
$this->$fn() :
$this->$p; // simulate an error
}
// this will be called every time
function get_rand() {
return rand();
}
// this will be called once
function get_cached() {
return $this->cached = rand();
}
}
$a = new LazyLoader;
var_dump($a->pub); // getter not called
var_dump($a->rand); // getter called
var_dump($a->rand); // once again
var_dump($a->cached); // getter called
var_dump($a->cached); // getter NOT called,response cached
var_dump($a->notreally); // error!
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
