文章出處
文章列表
探究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();
文章列表
全站熱搜