__get,__set 为php的magic方法,在类中定义为 public 类型。
class UserModel
{
private $id;
public $name;
public function __get($property_name)
{
if(isset($this->$property_name))
{
return($this->$property_name);
}else
{
return(NULL);
}
}
public function __set($property_name, $value)
{
$this->$property_name = $value;
}
}
定义:
$user=new UserModel();
1、直接赋值,读取private属性,将会调用__set,__get方法
echo $user->id;
2、为对象设置匿名属性。
echo $user->r ; // 触发 __get,第二次读取将不会触发__get方法 $user->r ='rhythmk' ; // 触发 __set,第二次赋值将不会触发__set方法
注意:
当对象的属性 如果 isset(对象->属性) == true, 将不会触发 __set,__get 方法。