PHP类(三)-类的封装

设置私有成员

使用private关键字来设置私有成员,完成对成员的封装,封装后的成员在对象的外部不能被访问,如果访问会出现错误,在对象的内部能访问被封装的成员属性和方法。

<?php
	class Person{
		//封装属性
		private $name;
		private $age;
		private $sex;
		
		function __construct($name="Tom",$age=23,$sex="Male"){
			$this->name = $name;
			$this->age = $age;
			$this->sex = $sex;
		}
		
		function Say(){
			echo "My name is ".$this->name.",and my age is ".$this->age.",sex is ".$this->sex;
		}
		
		private function Walk(){
			echo $this->name." is Walk.";
		}
	}
	
	$p1 = new Person();
	$p1->Say();
	$p1->Walk();
	$p1->age = 25;
?>

 执行结果

My name is Tom,and my age is 23,sex is Male
Fatal error: Call to private method Person::Walk() from context '' in C:\phpStudy\WWW\php\lei\FengZhuang.php on line 25
Fatal error: Cannot access private property Person::$age in C:\phpStudy\WWW\php\lei\FengZhuang.php on line 26

 私有成员的访问

在对象外如果想获取私有属性的值,或者想给私有属性赋值,可以使用public关键字或者在对象内部声明一些操作私有属性的方法

类中的构造方法默认为公有方法,构造方法不要设置成私有的

 

<?php
	class Person{
		private $name;
		private $age;
		private $sex;
		
		function __construct($name="Tom",$age=23,$sex="Male"){
			$this->name = $name;
			$this->age = $age;
			$this->sex = $sex;
		}
		
		function Say(){
			echo "My name is ".$this->name.",and my age is ".$this->age.",sex is ".$this->sex;
			echo "<br>";
		}
		
		public function Walk(){
			echo $this->name." is Walk.";
			echo "<br>";
		}
		
		public function SetAge($age){
			if($age >100 || $age <0)
				return;
			else
				$this->age = $age;
				return $this->age;
		}
	}
	
	$p1 = new Person();
	$p1->Say();
	$p1->Walk();
	$p1->SetAge(53);
?>

 运行结果

 

posted @ 2017-12-29 23:54  Sch01aR#  阅读(510)  评论(0编辑  收藏  举报