- 相關(guān)推薦
如何用php構(gòu)造函數(shù)的小例子
本文介紹下,php編程中有關(guān)構(gòu)造函數(shù)的二個(gè)例子,幫助大家理解與應(yīng)用php構(gòu)造函數(shù),感興趣的朋友可以參考學(xué)習(xí)下。
本節(jié)內(nèi)容:
php構(gòu)造函數(shù)
什么是構(gòu)造函數(shù)?
PHP網(wǎng)站中關(guān)于構(gòu)造函數(shù)的定義:
構(gòu)造函數(shù)是類中的一個(gè)特殊函數(shù),當(dāng)使用 new 操作符創(chuàng)建一個(gè)類的實(shí)例時(shí),構(gòu)造函數(shù)將會(huì)自動(dòng)調(diào)用。當(dāng)函數(shù)與類同名時(shí),這個(gè)函數(shù)將成為構(gòu)造函數(shù)。如果一個(gè)類沒有構(gòu)造函數(shù),則調(diào)用基類的構(gòu)造函數(shù),如果有的話,則調(diào)用自己的構(gòu)造函數(shù)
例子,a.php一個(gè)class a類:
復(fù)制代碼 代碼示例:
<?php
class a{
function __construct(){
echo 'class a';
}
}
b.php有個(gè)class b類繼承a類:
復(fù)制代碼 代碼示例:
<?php
include 'a.php';
class b extends a{
function __construct(){
echo '666666';
//parent::__construct();
}
function index(){
echo 'index';
}
}
$test=new b();
b類有自己的構(gòu)造函數(shù),那么實(shí)例化b類時(shí),自動(dòng)運(yùn)行構(gòu)造函數(shù),此時(shí)默認(rèn)不運(yùn)行父類的構(gòu)造函數(shù),如果同時(shí)要運(yùn)行父類構(gòu)造函數(shù),要聲明parent::__construct();
例如:
復(fù)制代碼 代碼示例:
<?php
include 'a.php';
class b extends a{
function index(){
echo 'index';
}
}
$test=new b();
此時(shí)b類沒有自己的構(gòu)造函數(shù),那么將默認(rèn)執(zhí)行父類的構(gòu)造函數(shù)。
【如何用php構(gòu)造函數(shù)的小例子】相關(guān)文章:
PHP類與構(gòu)造函數(shù)07-01
PHP函數(shù)的區(qū)別及用法10-27
PHP內(nèi)部函數(shù)的定義07-04
PHP常用函數(shù)總結(jié)10-21
PHP基本函數(shù)介紹10-25
PHP常用函數(shù)匯總09-07