一般来说,把类中的成员属性定义为private更符合现实的逻辑,能够更好的对类中成员起到保护作用。但是,对成员属性的读取和赋值操作都是非常频繁的,而如果在类中为每个
私有属性都定义可以在对象的外部获取和赋值的公有方法又是非常繁琐的。__set()和__get()正好是用来完成对所有私有属性都能获取和赋值的操作。
1、魔术方法__set()
<?php
class Person{
private $name;
private $age;
private $sex;
public function __construct($name,$age,$sex){
$this->name=$name;
$this->age=$age;
$this->sex=$sex;
}
//为私有属性赋值时自动调用,并且可以自定义赋值规则
public function __set($propertyName,$propertyValue){
if($propertyName=='sex'){
if(!($propertyValue=='male' || $propertyValue=='female')){
//如果非法赋值则返回空
echo "sex must be male or female<br/>";
return;
}
}
if($propertyName=='age'){
if($propertyValue>150 || $propertyValue<0){
echo "the age must between 0 and 150<br/>";
return;
}
}
$this->$propertyName=$propertyValue;
}
public function speek(){
echo 'my name is '.$this->name.'--'.$this->sex.'--'.$this->age.'<br/>';
}
}
$per1=new Person("tony",22,"male");
$per1->speek();
//下面将自动调用__set()方法
$per1->name="jack";
$per1->age=23;
$per1->sex="female";
$per1->speek();
//非法赋值
$per1->sex="secret";
$per1->age=156;
$per1->speek();
?>
输出结果:
my name is tony--male--22
my name is jack--female--23
sex must be male or female
the age must between 0 and 150
my name is jack--female--23
2、魔术方法__get()
<?php
class Person{
private $name;
private $age;
private $sex;
public function __construct($name,$age,$sex){
$this->name=$name;
$this->age=$age;
$this->sex=$sex;
}
//为私有属性赋值时自动调用,并且可以自定义赋值规则
public function __get($propertyName){
if($propertyName=='sex'){
return "the sex is secret";
}else{
return $this->$propertyName;
}
}
}
$per=new Person("tony",22,"male");
echo "Name:".$per->name."<br/>";
echo "Age:".$per->age."<br/>";
echo "Sex:".$per->sex."<br/>";</code></pre>
输出结果:
Name:tony
Age:22
Sex:the sex is secret