本文实例讲述了php使用类继承解决代码重复的问题。分享给大家供大家参考。具体分析如下:
继承直白地说就是给一个类建一个或多个子类,要创建子类就必须在类声明中使用 extends 关键字,新类名在前,extends 在中,父类名在后。
下例中,我们创建两个新类,BookProduct 和Cdproduct ,它们都继承自 ShopProduct 类。
class CdProduct extends ShopProduct {
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 {
function getNumberOfPages(){
return $this -> numPages;
}
function getSummaryLine(){
$base = \"{$this->title}( {$this->producerMainName},\";
$base .= \"{$this->producerFirstName} )\";
$base .= \":page cont - {$this->numPages} )\";
return $base;
}
}
?>
本文地址:https://www.stayed.cn/item/2480
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我