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