<?php
// 重载:
class Demo3
{
private $name;
private $salary;
protected $secret = '其实猪哥与朱老师不是同一个人';
// 构造方法
public function __construct($name, $salary)
{
$this->name = $name;
$this->salary = $salary;
}
// public function getName(){
// return $this->name;
// }
// public function getSalary(){
// return $this->salary;
// }
//魔术方法:__get($name)当获取未定义可不见属性时触发
public function __get($name){
// $name:要访问的属性名称
if ($name==='secret'){
return ($this->name==='admin')?$this->$name:'无权查看';
}
return $this->$name;
}
// 魔术方法:__set($name, $value)当设置未定义可不见属性赋值时触发
public function __set($name, $value)
{
// 直接返回, 极少这样做
// $this->$name = $value;
// 添加过滤机制
if ($name === 'salary') {
return $this->name === 'admin' ? $this->$name = $value : '无权更新';
}
return $this->$name = $value;
}
}
$obj = new Demo3('admin', 6666);
echo $obj->name, '<br>';
echo $obj->secret, '<br>';
$obj->salary=10000;
echo '工资是:'.$obj->salary.'<br>';
//if(isset($obj->name)){
// echo "你好";
//}
//else{
// echo "失败";
//}