Blogger Information
Blog 5
fans 0
comment 0
visits 10645
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
对象私有属性的封装与访问 4个魔术方法
勇往直前
Original
929 people have browsed it

实例

<?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
?>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post