作者:革斤Hero_394 | 来源:互联网 | 2014-06-17 17:33
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- class Person{
-
-
- private $name;
- private $age;
- private $sex;
-
-
- private __unset($proName){
- unset($this->$proName);
-
- }
-
-
-
-
- private function __isset($proName){
- return isset($this->$proName);
- }
-
- function __construct($name,$age,$sex){
- $this->name=$name;
- $this->age=$age;
- $this->sex=$sex;
-
- }
-
-
-
- private function __get($proName)
- {
-
- if($proName=="age"){
- if($this-age>40)
- return $this->age-10;
- }
- return $this->$proName;
- }
-
-
- private function __set($proName,$proValue){
-
-
- if($proName=="age"){
- if($proValue > 100 || $proValue<0)
- return;
- }
- $this->$proName=$proValue;
-
-
- }
-
-
- function setAge($age){
-
- if($age > 100 || $age < 0 )
- return;
- $this->age=$age;
- }
-
-
- function getAge(){
-
- if($this->age < 30)
- return $this->age;
- else if($this->age<40)
- return $this->age-5;
- else if($this->age<50)
- return $this->age;
- else
- return $this->age-15;
- 提供公有方法来 }
-
- function say(){
- echo "我的名字:{$this->name},我的年龄:{$this->age},我的姓别:{$this->sex}
";
-
-
- $this-run();
- }
-
- private function run(){
- echo &#39;111111111111
&#39;
-
- }
-
- function eat(){
-
- }
-
-
- function __destruct(){
-
- }
- }
-
- $p1=new Person("zhangsan",25,"男");
- $p2=new Person;
- $p3=new Person;
-
- $p1->setAge(30);
- $p1->getAge();
-
-
-
-
- $p1->say();
- $p1->run();
-
-
- unset($p1->name);
-
-
- if(isset($p1->name)){
-
- echo "存在
";
- }else{
- echo "没有这个成员
";
- }
-
-
- 来的成员:
- var $name;
- var $sex;
- var $age;
- function run(){…….}
- 改成封装的形式:
- private $name;
- private $sex;
- private $age;
- private function run(){……}
- 注意:只要是成员属性前面有其它的关键字就要去掉原有的关键字“var”。
- 通过private就可以把人的成员(成员属性和成员方法)封装上了。封装上的成员就不能被类外面直接访问了,只有对象内部自己可以访问;下面的代码会产生错误:
- class Person
- {
-
- private $name;
- private $sex;
- private $age;
-
- function say()
- {
- echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."
";
- }
-
- private function run()
- {
- echo "这个人在走路";
- }
- }
-
- $p1=new Person();
-
- $p1->name="张三";
- $p1->sex="男";
- $p1->age=20;
-
- echo $p1->name.”
”;
- echo $p1->sex.”
”;
- echo $p1->age.”
”
-
- $p1->run();
-
-
-
-
-
-
- ?>
从上面的实例可以看到,私有的成员是不能被外部访问的,因为私有成员只能在本对象内部自己访问,比如,$p1这个对象自己想把他的私有属性说出去,在say()这个方法里面访问了私有属性,这样是可以,(没有加任何访问控制,默认的是public的,任何地方都可以访问).