php使用类继承解决代码重复的问题
前端之家收集整理的这篇文章主要介绍了
php使用类继承解决代码重复的问题,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
本文实例讲述了PHP使用类继承解决代码重复的问题。分享给大家供大家参考。具体分析如下:
继承直白地说就是给一个类建一个或多个子类,要创建子类就必须在类声明中使用 extends 关键字,新类名在前,extends 在中,父类名在后。
下例中,我们创建两个新类,BookProduct 和Cdproduct ,它们都继承自 ShopProduct 类。
<div class="codetitle"><a style="CURSOR: pointer" data="84450" class="copybut" id="copybut84450" onclick="doCopy('code84450')"> 代码如下:
<div class="codebody" id="code84450"><?php
header('Content-type:text/html;charset=utf-8');
// 从这篇开始,类名首字母一律大写,规范写法
class ShopProduct{ // 声明类
public $numPages; // 声明属性
public $playLenth;
public $title;
public $producerMainName;
public $producerFirstName;
public $price;
function __construct($title,$firstName,$mainName,$price,$numPages=0,$playLenth=0){
$this -> title = $title; // 给
属性 title 赋传进来的值
$this -> producerFirstName= $firstName;
$this -> producerMainName = $mainName;
$this -> price= $price;
$this -> numPages= $numPages;
$this -> playLenth= $playLenth;
}
function getProducer(){ // 声明
方法
return "{$this -> producerFirstName }"."{$this -> producerMainName}";
}
function getSummaryLine(){
$base = "{$this->title}( {$this->producerMainName},";
$base .= "{$this->producerFirstName} )";
return $base;
}
}
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;
}
}
?>