访问控制

探究public , private , protected三种类型的数据的访问控制

其中public能被自身 , 子类 ,外部 访问;

protected 能被自身和子类访问,不能被外部直接访问;

private 只能被自身访问,不能被子类和外部访问。

 1 <?php
 2 
 3 class Human{
 4     public $name;
 5     protected $height;  //只有自身和子类能被访问
 6     public $weight;
 7     private $isHungry = true;  //不能被子类访问
 8 
 9     public function eat($food) {
10         echo $this->name." is eating ".$food."<br/>";
11     }
12 
13     public function info() {
14         //通过自身调用private数据传到外部
15         echo "HUMAN:".$this->name.";".$this->height.";".$this->isHungry ."<br/>";
16     }
17 }
18 
19 
20 class NbaPlayer extends Human{
21     
22     public $team="Bull";
23     public $playerNumber="23";
24 
25     private $age = "40";//private的类成员只能在内部被访问
26 
27     function __construct($name,$height,$weight,$team,$playerNumber) {
28         echo "In NbaPlayer constructor"."<br/>";
29         $this->name = $name; 
30         $this->height = $height;
31         $this->weight = $weight;
32         $this->team = $team;
33         $this->playerNumber = $playerNumber;
34       //  echo $this->isHungry."<br/>";  调用出错
35     }
36 
37     function __destruct() {
38         echo "Destroying".$this->name."<br/>";
39     }
40 
41     //方法定义
42     public function run() {
43         echo "Running"."<br/>";
44     }
45 
46     public function jump() {
47         echo "Jumping"."<br/>";
48     }
49     public function dribble() {
50         echo "Dribbling"."<br/>";
51     }
52     public function shoot() {
53         echo "shooting"."<br/>";
54     }
55     public function dunk() {
56         echo "Dunking"."<br/>";
57     }
58     public function pass() {
59         echo "passing"."<br/>";
60     }
61 
62     public function getAge() {  //通过子类调用protected的数据,传到外部访问
63         //外部不能直接访问,所以可以在内部对数据进行改动,使外部不能得到真实数据
64         echo $this->name."'s age is ".($this->age-2) ."<br/>";  
65     }
66 }
67 
68 $jordan = new NbaPlayer("Jordan","198cm","98kg","Bull","23");
69  $jordan->getAge() ."<br/>";
70  //$jordan->height;  直接访问height会出错
71 
72  $jordan->info();

 

posted @ 2015-07-04 10:52  todaytoday  阅读(246)  评论(0编辑  收藏  举报