php使用类继承解决代码重复的问题

前端技术 2023/09/01 PHP

本文实例讲述了php使用类继承解决代码重复的问题。分享给大家供大家参考。具体分析如下:

继承直白地说就是给一个类建一个或多个子类,要创建子类就必须在类声明中使用 extends 关键字,新类名在前,extends 在中,父类名在后。
 
下例中,我们创建两个新类,BookProduct 和Cdproduct ,它们都继承自 ShopProduct 类。

复制代码 代码如下:
<?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;
 }
}
?>

本文地址:https://www.stayed.cn/item/2480

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。