1 <?php 2 3 class Mouse 4 { 5 private $color; 6 public $sex; 7 8 public function __construct($role){ 9 switch($role){ 10 case 'pa': 11 $this->color = 'black'; 12 $this->sex = 'male'; 13 break; 14 case 'ma': 15 $this->color = 'white'; 16 $this->sex = 'female'; 17 break; 18 default: 19 throw new Exception('pa Or ma,please!'); 20 } 21 } 22 23 public function getColor(Mouse $mouse){ 24 if($mouse->sex == $this->sex){ 25 var_dump($this->color); 26 }else{ 27 var_dump('*****'); 28 } 29 } 30 31 public function mateWithMa(Mouse $ma){ 32 if($this->sex == 'male' && $ma->sex = 'female'){ 33 var_dump('You have been trust by ma'); 34 $ma->color = $this->color; 35 var_dump("success to mate! ma's color :" .($ma->color)); 36 } 37 } 38 39 public function mateWithPa(Mouse $pa){ 40 if($this->sex == 'female' && $pa->sex == 'male'){ 41 var_dump('You have been trust by pa'); 42 $pa->color = $this->color; 43 var_dump("success to mate! pa's color :" .($pa->color)); 44 } 45 } 46 } 47 48 var_dump('The First Couple :'); 49 $pa1 = new Mouse('pa'); 50 $ma1 = new Mouse('ma'); 51 $pa1->mateWithMa($ma1); 52 $ma1->mateWithPa($pa1); 53 54 echo " "; 55 56 var_dump('The Second Couple :'); 57 $pa2 = new Mouse('pa'); 58 $ma2 = new Mouse('ma'); 59 $ma2->mateWithPa($pa2); 60 $pa2->mateWithMa($ma2);
此文相关php知识点见 :http://www.php-internals.com/book/?p=chapt05/05-03-class-visibility