Home  >  Article  >  php教程  >  php (十三) 面向对象 封装

php (十三) 面向对象 封装

WBOY
WBOYOriginal
2016-06-21 08:48:431022browse

面向对象的封装性:

1,就是把对象的成员(属性,方法)结合成一个独立的相同单位,并尽可能隐藏对象的内部细节

public protected

private 私有的,用这个关键字修饰的成员,只能在对象内部访问(只有用$this访问),不能在对象外部使用

 

示例:

 

class Person{  
private $name;  
private $age;  
private $sex;  
function __construct($name="",$age=20,$sex="male"){  
$this->name=$name;  
$this->age=$age;  
$this->sex=$sex;  
}  
function getPro($name){  
return $this->$name;  
}  
function setAge($age){  
if($age>100$age<0){  
return;  
}  
$this->age=$age;  
}  
function getAge(){  
if($this->age<30){  
return $this->age;  
}elseif($this->age<40){  
return $this->age-5;  
}elseif($this->age<50){  
return $this->age-10;  
}else{  
return $this->age-15;  
}  
}  
function say(){  
echo "我的名字是:".$this->name.",年龄是:".$this->age.",性别是:".$this->sex.&#39;<br>&#39;;  
}  
function __destruct(){  
echo $this->name.",再见"."<br>";  
}  
}  
$p1=new Person("rayhooo",26,"male");  
$p1->say();  
echo $p1->getPro("name").&#39;<br>&#39;;  
$p1->setAge(45);  
echo $p1->getAge().&#39;<br>&#39;;  

 

 



Statement:
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