php如何呼叫父類別建構方法?
php
php呼叫父類別建構方法:使用parent呼叫父類別的建構,用【::】引用一個類,程式碼為【parent::__construct($title,$firstName,$mainName,$price) 】。
php呼叫父類別建構方法:
使用parent
呼叫父類別的構造方法
要引用一個類別而不是物件的方法,可以使用::
(兩個冒號),而不是->
。
所以, parent::__construct()
為著呼叫父類別的 __construct()
方法。
具體程式碼如下:
<?php header('Content-type:text/html;charset=utf-8'); // 从这篇开始,类名首字母一律大写,规范写法 class ShopProduct{ // 声明类 public $title; // 声明属性 public $producerMainName; public $producerFirstName; public $price; function __construct($title,$firstName,$mainName,$price){ $this -> title = $title; // 给属性 title 赋传进来的值 $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; } } ?>
登入後複製
每個子類別都會在設定自己的屬性前呼叫父類別的建構方法。基類(父類)現在只知道自己的數據,而我們也應該盡量避免告訴父類任何關於子類的信息,這是一條經驗規則,大家想想如果某個子類的信息應該是」保密「的,結果父類別知道它的訊息,其它子類別可以繼承,這樣子類別的資訊就不保密了。
#相關學習推薦:PHP程式設計從入門到精通
以上是php如何呼叫父類別建構方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前
By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
R.E.P.O.保存文件位置:在哪里以及如何保護它?
3 週前
By DDD

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

適用於 Ubuntu 和 Debian 的 PHP 8.4 安裝和升級指南

如何設定 Visual Studio Code (VS Code) 進行 PHP 開發
