一、魔术方法时以两个下划线"__"开头、具有特殊作用的一些方法,可以看作PHP的“语法糖”。
1、__set、__get是两个比较重要的魔术方法。其作用为:当给对象属性赋值或取值时,即使这个属性不存在,也不会报错,会 自动执行__set、__get方法,一定程度上增强了程序的健壮性。下边有个好玩的用法,仅供欣赏:
//输出最终所有条件
class Learn1 {
private $status;//status1,status2,status3,status4 分别代表4种筛选条件
private $status1;//权重分别为1、2、4、8
private $status2;
private $status3;
private $status4;
public function index(){
}
public function __set ( $name , $value ) {
$this->$name=$value;
}
public function __get ( $name ) {
if($name =='status' && $this->$name !='null'){
$status=0;
if($this->status1==1){
$status +=1;
}
if($this->status2==1){
$status +=2;
}
if($this->status3==1){
$status +=4;
}
if($this->status4==1){
$status +=8;
}
return $status;
}else{
return $this->$name;
}
}
$test=new Learn1();
$test->status1=1;
$test->status2=1;
echo $test->status;//最终条件