關於php中建構函式的範例程式碼分享

來源:互聯網
上載者:User
本文將使用執行個體講解php建構函式的使用方法

PHP官網定義:

建構函式是類中的一個特殊函數,當使用 new 操作符建立一個類的執行個體時,建構函式將會自動調用。當函數與類同名時,這個函數將成為建構函式。如果一個類沒有建構函式,則調用基類的建構函式,如果有的話,則調用自己的建構函式


如a.php一個class a類:

<?phpclass a{ function construct(){  echo 'class a'; }}


b.php有個class b類繼承a類:

<?phpinclude 'a.php';class b extends a{ function construct(){  echo '666666';  //parent::construct(); } function index(){  echo 'index'; }}


$test=new b();
這樣寫的話,b類有自己的建構函式,那麼執行個體化b類的時候,自動運行建構函式,此時預設不運行父類的建構函式,如果同時要運行父類建構函式,要聲明parent::construct();

<?phpinclude 'a.php';class b extends a{ function index(){  echo 'index'; }}


$test=new b();
此時b類沒有自己的建構函式,那麼將預設執行父類的建構函式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.