本文实例讲述了php实现parent调用父类的构造方法与被覆写的方法。分享给大家供大家参考。具体分析如下:
覆写:被重新设计。
在子类中定义构造方法时,需要传递参数给父类的构造方法,否则我们得到的可能是一个构造不完整的对象。
要调用父类的方法,首先要找到一个引用类本身的途径:句柄(handle),PHP为此提供了parent关键字。
parent 调用父类的构造方法
要引用一个类而不是对象的方法,可以使用 ::(两个冒号),而不是 ->。
所以, parent::__construct() 以为着调用父类的 __construct() 方法。
修改上篇《使用类继承解决代码重复等问题》中的代码,让每个类只处理自己的数据:
复制代码 代码如下:<"{$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;
}
}
"codetitle">复制代码 代码如下:// 父类: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;
}
我们在父类 ShopProduct 中为 getSummaryLine() 方法完成了”核心“功能,接着在子类中简单的调用父类的方法,然后增加更多数据到摘要字符串,方法的拓展就实现了。
希望本文所述对大家的php程序设计有所帮助。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 王子异《1996 Part.2》[320K/MP3][18.29MB]
- 群星.1994-宝丽金最倾情3CD【宝丽金】【WAV+CUE】
- 乐俊亨.2024-同泪【CharioticMusic】【FLAC分轨】
- 何耀珊.2006-收获【华纳】【WAV+CUE】
- 梁汉文1994-壹精选[华星][WAV+CUE]
- 洪荣宏1981-歹路不可行·相思雨(飞跃复刻版)[光美][WAV+CUE]
- 旅行团2015-10Day’s[来福胶泥][WAV+CUE]
- 龙千玉.2011-卡将哟【豪记】【WAV+CUE】
- 蔣志光.1993-多情多寂寞(国专)【BMG】【WAV+CUE】
- 陈慧娴.1996-雪映美白96演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 王子异《1996 Part.2》[FLAC/分轨][50.66MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[320K/MP3][155.91MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[FLAC/分轨][251.78MB]
- 黄韵玲2001-巴结音乐[全员集合][WAV+CUE]
- 郑绪岚2015-流金岁月·精选[首版][WAV+CUE]