【发布时间】:2015-01-25 09:24:43
【问题描述】:
我是 php 新手。我知道 __set() 和 __get() 创建受保护的属性,但它的行为类似于公共属性。并且通过此方法创建的属性设置为受保护。但唯一的区别是它们可以通过任何方式访问时间从任何地方就像公共属性一样。由于我没有任何 php 的实际工作经验,我想知道 为什么不创建公共属性而不是使用 __get() 和 __set 的麻烦()?? __set() 属性还会在运行时创建属性。在跟踪对象的所有属性时是否会产生问题? ?
class foo {
protected $another='lol'; //protected property
public function __get($name) {
return $this->$name;
}
public function __set($name, $value) {
$this->$name = $value;
}
}
class bar extends foo{ // inherits from foo
public function __get($name){ //__get() method for bar class
return $this->$name; //
}
}
$foo = new foo();
$foo->bar = 'test';
echo $foo->another; //echos protected property from parent class
echo '</br>';
$bar=new bar();
echo $bar->another; // echos inherited private property from parent class
var_dump($foo);
【问题讨论】:
-
看看here,也可以考虑阅读Why use getters/setters