php calls the parent class constructor: use parent to call the parent class's constructor, use [::] to reference a class, the code is [parent::__construct($title,$firstName,$mainName,$price) 】.
php calls the parent class constructor:
Use parent
to call the parent class constructor Method
To refer to a method of a class rather than an object, use ::
(two colons) instead of ->
.
So, parent::__construct()
In order to call the __construct()
method of the parent class.
The specific code is as follows:
<?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; } } ?>
Each subclass will call the constructor of the parent class before setting its own properties. The base class (parent class) now only knows its own data, and we should try to avoid telling the parent class any information about the subclass. This is a rule of thumb. Think about it if the information of a certain subclass should be "confidential" , as a result, the parent class knows its information, and other subclasses can inherit it, so that the subclass's information is not kept confidential.
Related learning recommendations: PHP programming from entry to proficiency
The above is the detailed content of How to call the parent class constructor in php?. For more information, please follow other related articles on the PHP Chinese website!