建構函式和解構函式

來源:互聯網
上載者:User

標籤:

首先建立一個類,然後加入方法,並使用建構函式和解構函式

 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

是在一起被解構函式析構的。

建構函式和解構函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.