如何用php構造函數(shù)的小例子
本文介紹下,php編程中有關構造函數(shù)的二個例子,幫助大家理解與應用php構造函數(shù),感興趣的朋友可以參考學習下。
本節(jié)內(nèi)容:
php構造函數(shù)
什么是構造函數(shù)?
PHP網(wǎng)站中關于構造函數(shù)的定義:
構造函數(shù)是類中的一個特殊函數(shù),當使用 new 操作符創(chuàng)建一個類的實例時,構造函數(shù)將會自動調(diào)用。當函數(shù)與類同名時,這個函數(shù)將成為構造函數(shù)。如果一個類沒有構造函數(shù),則調(diào)用基類的構造函數(shù),如果有的話,則調(diào)用自己的構造函數(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';
/pic/p>
}
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構造函數(shù)的小例子】相關文章:
PHP類與構造函數(shù)11-09
PHP語言構造器介紹09-18
php數(shù)學常用函數(shù)09-15
PHP函數(shù)知識總結09-22
PHP內(nèi)部函數(shù)的定義01-23
PHP常用函數(shù)總結03-10