|
php官網(wǎng)定義:
復(fù)制代碼 代碼如下:
構(gòu)造函數(shù)是類中的一個特殊函數(shù),當(dāng)使用 new 操作符創(chuàng)建一個類的實(shí)例時,構(gòu)造函數(shù)將會自動調(diào)用。當(dāng)函數(shù)與類同名時,這個函數(shù)將成為構(gòu)造函數(shù)。如果一個類沒有構(gòu)造函數(shù),則調(diào)用基類的構(gòu)造函數(shù),如果有的話,則調(diào)用自己的構(gòu)造函數(shù)
如a.php一個class a類:
復(fù)制代碼 代碼如下:
<?php
class a{
function __construct(){
echo 'class a';
}
}
b.php有個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類的時候,自動運(yùn)行構(gòu)造函數(shù),此時默認(rèn)不運(yùn)行父類的構(gòu)造函數(shù),如果同時要運(yùn)行父類構(gòu)造函數(shù),要聲明parent::__construct();
復(fù)制代碼 代碼如下:
<?php
include 'a.php';
class b extends a{
function index(){
echo 'index';
}
}
$test=new b();
此時b類沒有自己的構(gòu)造函數(shù),那么將默認(rèn)執(zhí)行父類的構(gòu)造函數(shù)。
php技術(shù):php構(gòu)造函數(shù)實(shí)例講解,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。