標籤:
首先建立一個類,然後加入方法,並使用建構函式和解構函式
1 <?php 2 3 class NbaPlayer { 4 public $name="Jordan"; 5 public $height="198cm"; 6 public $weight="98kg"; 7 public $team="Bull"; 8 public $playerNumber="23"; 9 10 //建構函式,在對象被執行個體化的時候自動調用11 function __construct($name,$height,$weight,$team,$playerNumber) {12 echo "In NbaPlayer constructor"."<br/>";13 $this->name = $name; //$this 是php裡面的偽變數,表示對象自身,可以通過$this->的方式訪問對象的屬性和方法14 $this->height = $height;15 $this->weight = $weight;16 $this->team = $team;17 $this->playerNumber = $playerNumber;18 }19 20 //解構函式,程式執行結束的時候自動調用,不需要new21 //解構函式通常被用於清理程式使用的資源,比如程式使用了印表機,那麼可以在解構函式裡面釋放印表機資源22 function __destruct() {23 echo "Destroying".$this->name."<br/>";24 }25 26 //方法定義27 public function run() {28 echo "Running"."<br/>";29 }30 31 public function jump() {32 echo "Jumping"."<br/>";33 }34 public function dribble() {35 echo "Dribbling"."<br/>";36 }37 public function shoot() {38 echo "shooting"."<br/>";39 }40 public function dunk() {41 echo "Dunking"."<br/>";42 }43 public function pass() {44 echo "passing"."<br/>";45 }46 }47 48 $jordan = new NbaPlayer("Jordan","198cm","98kg","Bull","23");49 echo $jordan->name."<br/>";50 $jordan->dribble();51 $jordan->pass();52 53 $james = new NbaPlayer("James","203cm","120kg","Heat","6");54 echo $james->name."<br/>";55 //通過把變數設定為null,可以觸發解構函式的調用56 $james1= $james; 57 $james2=&$james;//加&符號表示與$james是同一個引用,沒有建立新的引用58 $james2 = null;//要把所有的引用函數設為null,才能夠使該函數使用解構函式59 $james1 = null;60 echo "from now on James will not be used"."<br/>";
結果為:
1 In NbaPlayer constructor2 Jordan3 Dribbling4 passing5 In NbaPlayer constructor6 James7 DestroyingJames8 from now on James will not be used9 DestroyingJordan
此時因為 Jordan 函數沒有設定為null,故在最後是因為解構函式自動執行,所以 DestroyingJordan 了,
如果引用james函數時只設定了 $james1 = null; ,而$james2沒有設定為null,那麼到最後james最後被析構是因為被解構函式析構了,而不是設定為null的時候析構了。
原因是要把所有的引用函數設為null,才能夠使該函數使用解構函式。
引用函數沒有全部設定為null時,程式的輸出結果:
1 In NbaPlayer constructor2 Jordan3 Dribbling4 passing5 In NbaPlayer constructor6 James7 from now on James will not be used8 DestroyingJames9 DestroyingJordan
這時
1 DestroyingJames2 DestroyingJordan
是在一起被解構函式析構的。
建構函式和解構函式