您当前的位置: 首页 > 学无止境 > 网站建设 网站首页网站建设
燕十八魔术方法__set__get__unset__isset
发布时间:2015-09-02 09:33:55编辑:雪饮阅读()
__get
<?php
header("Content-type:text/html;charset=utf-8;");
class human{
public function __clone(){echo "雪饮忍法帖:影分身之术!";}
}
$a=new human();
$b=clone $a;
echo "<hr/>";
class human2{
private $money="30两";
protected $age=23;
public $name="lily";
public function __get($property){
echo "你想访问我的".$property."属性";
/*
当我们调用一个权限上不允许调用的属性时,__get魔术方法
会自动调用,并且自动传参,参数值时你调用的属性名
*/
}
}
$lily=new human2();
echo $lily->name;
echo "<br/>";
echo $lily->age;
echo "<br/>";
echo $lily->money;
echo "<br/>";
echo $lily->friends;
echo "<br/>";
/*通过对象来新增属性*/
$lily->aaa=111;
$lily->bbb=222;
print_r($lily);
?>
__set
<?php
header("Content-type:text/html;charset=utf-8;");
class human3{
private $money="30两";
protected $age=23;
public $name="hmm";
public function __set($a,$b){
echo "你想设置我的属性".$a."的值为".$b;
/*
使用print_r函数打印对象,发现并没有新增aaa的属性,说明已经被set魔术方法全权处理了
当对一个对象的不存在属性或者无权访问的属性进行赋值时会自动传递两个参数于set魔术方法之中,分别为属性名和属性值
*/
}
}
$c=new human3();
$c->aaa=111;
echo "<br/>";
print_r($c);
?>
__isset与__unset
<?php
header("Content-type:text/html;charset=utf-8;");
class dog{
public $leg=4;
protected $bone="猪腿骨";
public function __isset($p){
echo "你想判断我属性".$p."是否存在<br/>";
/*
当isset()判断对象不可见的属性时(protected/private/不存在的属性)
会引发__isset()来执行,此时的isset方法并不能正确判断一个属性的存在与否了。。。
*/
}
public function __unset($p){
echo "<br/>你想去掉我的属性".$p."????<br/>";
/*
当unset一个不存在或不可访问属性之时会自动触发_unset魔术方法
*/
}
}
$d=new dog();
if(isset($d->leg)){
echo "leg存在";
}
echo "<br/>";
if(isset($d->kk)){
echo "kk存在";
}
else{
echo "kk不存在";
}
echo "<hr/>";
echo "unset leg属性前:<br/>";
print_r($d);
echo "<br/>unset leg属性后:<br/>";
unset($d->leg);
print_r($d);
unset($d->bone);
?>
关键字词:燕十八,魔术方法,个人博客