这样做会被认为是好的做法吗…
我有以下定义的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方法,我使用了magic方法来为我需要的属性调用受人尊敬的getter,或者只返回属性的值而不做任何更改。这可以看作是一种好的做法吗?
最佳答案
不知道最佳实践,但当需要延迟加载属性时(例如,当获取涉及复杂钙化或数据库查询时),g e t会非常有用。此外,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!