<?php
// 对象的封装以及魔术方法
class Demo
{
private $name;
private $age;
private $salary;
public function __construct($name,$age,$salary)
{
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
//魔术方法__get使封装的属性能在外部访问
public function __get($attr)
{
return $this->$attr;
}
//__set可以在外部设置不可见的属性
public function __set($attr,$val)
{
$this->$attr = $val;
}
//魔术方法__isset
public function __isset($attr)
{
//如果想使某个属性不被访问到,可以做如下判断
if($attr == 'name'){
return false;
}
return isset($this->$attr);
}
//在外部删除不可见属性
public function __unset($attr)
{
unset($this->$attr);
}
}
$obj = new Demo('peter',28,4500);
//当用isset函数去判断一个对象的属性时,当对象的属性不可见或不存在时返回false,但如果对象里面定义了魔术方法__isset,那么不存在的属性依然返回false,而不可见的属性则返回true
echo isset($obj->name)?'存在':'不存在';
echo '<hr>';
echo $obj->name;
echo '<hr>';
$obj->name = 'Jim';
echo $obj->name;//Jim
echo '<hr>';
unset($obj->name);//会重新去调用魔术方法__unset
echo $obj->name;//Notice: Undefined property: Demo::$name
?>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号