本文實(shí)例講述了php實(shí)現(xiàn)parent調(diào)用父類的構(gòu)造方法與被覆寫的方法。分享給大家供大家參考。具體分析如下:
覆寫:被重新設(shè)計(jì)。
在子類中定義構(gòu)造方法時(shí),需要傳遞參數(shù)給父類的構(gòu)造方法,否則我們得到的可能是一個(gè)構(gòu)造不完整的對(duì)象。
要調(diào)用父類的方法,首先要找到一個(gè)引用類本身的途徑:句柄(handle),PHP為此提供了parent關(guān)鍵字。
parent 調(diào)用父類的構(gòu)造方法
要引用一個(gè)類而不是對(duì)象的方法,可以使用 ::(兩個(gè)冒號(hào)),而不是 ->。
所以, parent::__construct() 以為著調(diào)用父類的 __construct() 方法。
修改上篇《使用類繼承解決代碼重復(fù)等問題》中的代碼,讓每個(gè)類只處理自己的數(shù)據(jù):
header('Content-type:text/html;charset=utf-8');
// 從這篇開始,類名首字母一律大寫,規(guī)范寫法
class ShopProduct{ // 聲明類
public $title; // 聲明屬性
public $producerMainName;
public $producerFirstName;
public $price;
function __construct($title,$firstName,$mainName,$price){
$this -> id="code89833"> // 父類:ShopProduct
function getSummaryLine(){
$base = "{$this->title}( {$this->producerMainName},";
$base .= "{$this->producerFirstName} )";
return $base;
}
// 子類:CdProduct
function getSummaryLine(){
$base = parent::getSummaryLine();
$base .= ":playing time - {$this->playLength} )";
return $base;
}
// 子類:BookProduct
function getSummaryLine(){
$base = parent::getSummaryLine();
$base .= ":page cont - {$this->numPages} )";
return $base;
}
我們?cè)诟割?ShopProduct 中為 getSummaryLine() 方法完成了”核心“功能,接著在子類中簡(jiǎn)單的調(diào)用父類的方法,然后增加更多數(shù)據(jù)到摘要字符串,方法的拓展就實(shí)現(xiàn)了。
希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。