PHP学习笔记二: 面向对象设计

public 表示全局,类内部外部子类都可以访问;
 1 <?php
 2     
 3     class Test{
 4         public  $name='Janking',
 5                 $sex='male',
 6                 $age=23;
 7         
 8         function __construct(){
 9             echo $this->age.'<br />'.$this->name.'<br />'.$this->sex.'<br />';
10         }
11         
12          function func(){
13             echo $this->age.'<br />'.$this->name.'<br />'.$this->sex.'<br />';
14         }
15     }
16 
17 
18 $P=new Test();
19 echo '<br /><br />';
20 $P->age=100;
21 $P->name="Rainy";
22 $P->sex="female";
23 $P->func();
24 ?> 
Public
private表示私有的,只有本类内部可以使用;
 1 <?php
 2     
 3     class Test{
 4         private  $name='Janking',
 5                 $sex='male',
 6                 $age=23;
 7         
 8         function __construct(){
 9             $this->funcOne();
10         }
11         
12          function func(){
13             echo $this->age.'<br />'.$this->name.'<br />'.$this->sex.'<br />';
14         }
15         
16         private function funcOne(){
17             echo $this->age.'<br />'.$this->name.'<br />'.$this->sex.'<br />';
18         }
19     }
20 
21 
22 $P=new Test();
23 echo '<br /><br />';
24 $P->func();
25 $P->age=100;        // Cannot access private property Test::$age 
26 $P->name="Rainy";   // Cannot access private property Test::$name 
27 $P->sex="female";   // Cannot access private property Test::$female
28 $P->funcOne();      // Call to private method Test::funcOne() from context ''
29 ?> 
Private
protected表示受保护的,只有本类或子类或父类中可以访问;


 和封装有关的魔术方法:

 __set():是直接设置私有成员属性值时,自动调用的方法
 __get():是直接获取私有成员属性值时,自动调用的方法
 __isset(); 是直接isset查看对象中私有属性是否存时自动调用这个方法
 __unset(); 是直接unset删除对象中私有属性时,自动调用的方法

 
posted @ 2013-05-14 10:55  琅琊丶  阅读(331)  评论(0编辑  收藏  举报