PHP5中的getter和setter是什么?
有人能给我一个好的例子并解释一下吗?
class test {
private $count; //those who use your class are not able to see this property, only the methods above
public function setCount( $value )
{
//make some validation or manipulation on data here, if needed
$this->count = $value;
}
public function getCount()
{
return $this->count;
}
}
类的属性可以是私有的。这意味着只有对象才能读写自己的私有属性。因此需要使用方法来实现。读取并返回属性值的方法称为getter,写入属性的方法称为setter。通过这些方法,类可以控制输出和输入。这个概念被称为封装。
在PHP 5中,Getter和Setter是相当新的概念,以两个神奇的函数__get()和set()的形式出现。正如以下示例所解释的那样,这两个函数可以显着地设置或获取对象的属性值。
class Datatype{
private $thing;
public function _set($k,$v){
$this->$k = $v;
}
public function __get($k){
return $this->$k;
}
}