php 对象直接访问私有属性

WBOY
Release: 2016-06-23 13:24:39
Original
823 people have browsed it

<?php	header("content-type:text/html;charset=UTF-8");	class Person{		//私有的成员属性,对直接访问象		private $name;		private $age;		private $sex;				//魔术方法 __construct(), __set(), __unset(), __isset(), __unset().....		function __construct($name="name1",$age =20,$sex="女"){			$this->name=$name;			$this->age=$age;			$this->sex=$sex;		}				/*			输出 Cannot access private property Person::$name						对象不能直接访问和设置私有属性的值,但是通过魔术方法__get($proName), __set($proName,$proValue)可以做到.			步骤:				1.重写魔术方法__get($property) , __set($proName,$proValue)				2.用对象直接访问或设置私有属性					$p1->name="对象直接访问私有属性";					echo $p1->name;				3.对象直接访问或设置私有属性时,会自动调用魔法方法__get($proName), __set($proName,$proValue)		*/		function __get($proName){			return $this->$proName;		}				function __set($proName,$proValue){			$this->$proName=$proValue;		}				function say(){			echo "$this->name:我的年龄$this->age,性别:$this->sex<br>";		}				function run(){			$this->left();			$this->right();		}				private function left(){			echo "left";		}				private function right(){			echo "right";		}				//析构方法,对象销毁前自动调用		function __destruct(){			echo "$this->name:我走了<br>";		}	}	 	$p1 = new Person("name1",15,"女");	$p2 = new Person("name2",20,"男");	$p3 = new Person("name3",30,"女");					/*		对象直接访问或设置私有属性	*/	$p1->name="对象直接访问私有属性";	echo $p1->name."<br>";		/*	输出,注意__destruct()的输出顺序			name1:我的年龄15,性别:女		name2:我的年龄20,性别:男		name3:我的年龄30,性别:女				name1:我走了		name3:我走了		name2:我走了	*/	$p1->say();	$p2->say();	$p3->say();	$p1=null;		?>
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!