Blogger Information
Blog 48
fans 2
comment 3
visits 37449
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5月2日作业—魔术方法__get()和__set()
黑猫警长的博客
Original
608 people have browsed it

实例

<?php 
/**
* 
*/
class StaffInfo{
	private $name;
	private $age;
	private $sanwei;
	private $data=[];

	//构造方法
	public function __construct($name='',$age=0,array $sanwei=[])
	{
		$this->name = $name;
		$this->age = $age;
		$this->sanwei = $sanwei;
	}

	//魔术方法:查询器
	public function __get($name)
	{
		$msg = null;
		if(isset($this->$name)){
			$msg = $this->$name;
		}elseif(isset($this->data[$name])){
			$msg = $this->data[$name];
		}else{
			$msg = '没有找到这个属性';
		}
		return $msg;
	}

	//魔术方法:设置器
	public function __set($name,$value)
	{
		if (isset($this->name)) {
			$this->$name = $value;
		}else{
			$this->$data[$name] = $value;
		}
	}

}

运行实例 »

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

实例

<?php 

require './class/StaffInfo.php';
$staffinfo = new StaffInfo('朱老师',36,[65,65,65]);

//测试魔术方法 __get()
echo '姓名:',$staffinfo->name,'<br>';
echo '年龄:',$staffinfo->age,'<br>';
echo '三围:',print_r($staffinfo->sanwei,true),'<br>';
//测试一个不存在的属性
echo '爱好:',$staffinfo->aihao,'<br>';

echo '<br>';

//测试魔术方法 __set()
$staffinfo->name = '灭绝小师妹';
$staffinfo->age = 24;
$staffinfo->sanwei = [75,60,72];



echo '姓名:',$staffinfo->name,'<br>';
echo '年龄:',$staffinfo->age,'<br>';
// echo '身高:',print_r($staffinfo->sanwei,true),'<br>';
echo '胸围:',$staffinfo->sanwei[0],'<br>';
echo '腰围:',$staffinfo->sanwei[1],'<br>';
echo '臀围:',$staffinfo->sanwei[2],'<br>';
//测试一个自定义的属性
$staffinfo->kecheng = '前端';
echo '所教课程:',$staffinfo->kecheng,'<br>';

运行实例 »

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

QQ截图20180513162849.png



Correction status:Uncorrected

Teacher's comments:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!