面向对象的三大特性之一就是封装性。所以当申明字段时一般是申明私有字段。那么如何去读取或者修改这些字段呢,就要用到$this关键字。
首先我们创建一个类。
class Animal{
private $name = dog;
public function getname(){
return $this->name;
}
public function setname($value){
$this->name=$value;
}
}
如果当需要读取或修改字段时直接调用getname()和setname()方法了,但是如果当有大量属性时一个一个去写get,set方法就会非常麻烦。这时候就需要用到php拦截器_get(),_set()方法了。
先上代码:
class Animal{
private $name = dog;
private $age = 2;
private $weigth = 5;
public _get($name){
return $this->$name;
}
public _set($name,$value){
$this->$name=$value;
}
}
这时候无论想得到或改变哪些字段只需要调用这两个方法了
$cat = new Animal();
$cat->_set('name','lili');
$catname = $_get('name');
echo $catname;
这里就输出:lili了。
其实一般拦截器都是private方法,如:
class Animal{
private $name = dog;
private $age = 2;
private $weigth = 5;
private _get($name){
return $this->$name;
}
private _set($name,$value){
$this->$name=$value;
}
}
$cat = new Animal();
$cat->name;
$cat->name=lili;
这样子调用属性和修改属性也是可以的,这是为什么呢
这时候__set()和__get()方法私有了,还是可以执行,是因为目前程序的指针已经在类内了。而类内可以执行封装的方法,类内执行私有方法,不会出现任何错误。它只需要间接的拦截就可以了。拦截是在内类执行的。所以,__set()和__get()是PHP内置的方法,具有一定的特殊性。