創(chuàng)新互聯(lián)www.cdcxhl.cn八線動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買多久送多久,劃算不套路!
這篇文章將為大家詳細(xì)講解有關(guān)如何在php中調(diào)用父類構(gòu)造方法,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
php調(diào)用父類構(gòu)造方法:使用parent調(diào)用父類的構(gòu)造,用【::】引用一個(gè)類,代碼為【parent::__construct($title,$firstName,$mainName,$price)】。
php調(diào)用父類構(gòu)造方法:
使用parent
調(diào)用父類的構(gòu)造方法
要引用一個(gè)類而不是對(duì)象的方法,可以使用 ::
(兩個(gè)冒號(hào)),而不是 ->
。
所以, parent::__construct()
為著調(diào)用父類的 __construct()
方法。
具體代碼如下:
<?php 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 -> title = $title; // 給屬性 title 賦傳進(jìn)來的值 $this -> producerFirstName= $firstName; $this -> producerMainName = $mainName; $this -> price= $price; } function getProducer(){ // 聲明方法 return "{$this -> producerFirstName }"."{$this -> producerMainName}"; } function getSummaryLine(){ $base = "{$this->title}( {$this->producerMainName},"; $base .= "{$this->producerFirstName} )"; return $base; } } class CdProduct extends ShopProduct { public $playLenth; function __construct($title,$firstName,$mainName,$price,$playLenth){ parent::__construct($title,$firstName,$mainName,$price); $this -> playLenth= $playLenth; } function getPlayLength(){ return $this -> playLength; } function getSummaryLine(){ $base = "{$this->title}( {$this->producerMainName},"; $base .= "{$this->producerFirstName} )"; $base .= ":playing time - {$this->playLength} )"; return $base; } } // 定義類 class BookProduct extends ShopProduct { public $numPages; function __construct($title,$firstName,$mainName,$price,$numPages){ parent::__construct($title,$firstName,$mainName,$price); $this -> numPages= $numPages; } function getNumberOfPages(){ return $this -> numPages; } function getSummaryLine(){ $base = "{$this->title}( {$this->producerMainName},"; $base .= "{$this->producerFirstName} )"; $base .= ":page cont - {$this->numPages} )"; return $base; } } ?>
每個(gè)子類都會(huì)在設(shè)置自己的屬性前調(diào)用父類的構(gòu)造方法。基類(父類)現(xiàn)在僅知道自己的數(shù)據(jù),而我們也應(yīng)該盡量避免告訴父類任何關(guān)于子類的信息,這是一條經(jīng)驗(yàn)規(guī)則,大家想想如果某個(gè)子類的信息應(yīng)該是”保密“的,結(jié)果父類知道它的信息,其它子類可以繼承,這樣子類的信息就不保密了。
關(guān)于如何在php中調(diào)用父類構(gòu)造方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
本文名稱:如何在php中調(diào)用父類構(gòu)造方法-創(chuàng)新互聯(lián)
URL分享:http://m.newbst.com/article42/dceihc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、定制網(wǎng)站、移動(dòng)網(wǎng)站建設(shè)、關(guān)鍵詞優(yōu)化、品牌網(wǎng)站制作、網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容