PHP面向对象继承用法详解(优化与减少代码重复)


Posted in PHP onDecember 02, 2016

本文实例讲述了PHP面向对象继承用法。分享给大家供大家参考,具体如下:

继承

先看两个类

<?php
class CdProduct {
  public $playLength; // 播放时间
  public $title;
  public $producerMainName;
  public $producerFirstName;
  public $price;
  function __construct(  $title, $firstName,
              $mainName, $price,
              $playLength ) {
    $this->title       = $title;
    $this->producerFirstName = $firstName;
    $this->producerMainName = $mainName;
    $this->price       = $price;
    $this->playLength    = $playLength;
  }
  function getPlayLength() {
    return $this->playLength;
  }
  function getSummaryLine() {
    $base = "{$this->title} ( {$this->producerMainName}, ";
    $base .= "{$this->producerFirstName} )";
    $base .= ": playing time - {$this->playLength}";
    return $base;
  }
  function getProducer() {
    return "{$this->producerFirstName}".
        " {$this->producerMainName}";
  }
}
class BookProduct {
  public $numPages; // 看的页数
  public $title;
  public $producerMainName;
  public $producerFirstName;
  public $price;
  function __construct(  $title, $firstName,
              $mainName, $price,
              $numPages ) {
    $this->title       = $title;
    $this->producerFirstName = $firstName;
    $this->producerMainName = $mainName;
    $this->price       = $price;
    $this->numPages     = $numPages;
  }
  function getNumberOfPages() {
    return $this->numPages;
  }
  function getSummaryLine() {
    $base = "{$this->title} ( {$this->producerMainName}, ";
    $base .= "{$this->producerFirstName} )";
    $base .= ": page count - {$this->numPages}";
    return $base;
  }
  function getProducer() {
    return "{$this->producerFirstName}".
        " {$this->producerMainName}";
  }
}
$product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 );
print $product1->getSummaryLine();
print "\n";
$product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 );
print $product2->getSummaryLine();
print "\n";
?>

输出:

cd1 ( bobbleson, bob ): playing time - 50
book1 ( harrelson, harry ): page count - 30

点评:这两个类,代码重复性太高,有相同性,也有差异性。不如用继承来简化处理。

采用继承来处理

<?php
class ShopProduct {
  public $numPages;
  public $playLength;
  public $title;
  public $producerMainName;
  public $producerFirstName;
  public $price;
  function __construct(  $title, $firstName,
              $mainName, $price,
              $numPages=0, $playLength=0 ) {
    $this->title       = $title;
    $this->producerFirstName = $firstName;
    $this->producerMainName = $mainName;
    $this->price       = $price;
    $this->numPages     = $numPages;
    $this->playLength    = $playLength;
  }
  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 count - {$this->numPages}";
    return $base;
  }
}
$product1 = new CdProduct("cd1", "bob", "bobbleson", 4, null, 50 );
print $product1->getSummaryLine();
print "\n";
$product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 );
print $product2->getSummaryLine();
print "\n";
?>

输出:

cd1 ( bobbleson, bob ): playing time - 50
book1 ( harrelson, harry ): page count - 30

点评:继承处理很好的解决了差异性,相通性问题。

进一步优化处理

<?php
class ShopProduct {
  // 抽离出共有属性
  public $title;
  public $producerMainName;
  public $producerFirstName;
  public $price;
  function __construct(  $title, $firstName,
              $mainName, $price ) {
    $this->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 $playLength;
  function __construct(  $title, $firstName,
              $mainName, $price, $playLength ) {
    parent::__construct(  $title, $firstName,
                $mainName, $price ); // 继承父类的构造函数
    $this->playLength = $playLength; // 处理自己专有的属性
  }
  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 count - $this->numPages";
    return $base;
  }
}
$product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 );
print $product1->getSummaryLine();
print "\n";
$product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 );
print $product2->getSummaryLine();
print "\n";
?>

输出:

cd1 ( bobbleson, bob ): playing time - 50
book1 ( harrelson, harry ): page count - 30

点评:这里把共有属性在父类中,其他个性属性放在自己的类中处理。并设置自己的构造方法,继承父类的构造方法。

进一步继承父类的方法

<?php
class ShopProduct {
  public $title;
  public $producerMainName;
  public $producerFirstName;
  public $price;
  function __construct(  $title, $firstName,
              $mainName, $price ) {
    $this->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 $playLength;
  function __construct(  $title, $firstName,
              $mainName, $price, $playLength ) {
    parent::__construct(  $title, $firstName,
                $mainName, $price );
    $this->playLength = $playLength;
  }
  function getPlayLength() {
    return $this->playLength;
  }
  function getSummaryLine() {
    $base = parent::getSummaryLine();
    $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 = parent::getSummaryLine();
    $base .= ": page count - {$this->numPages}";
    return $base;
  }
}
$product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 );
print $product1->getSummaryLine();
print "\n";
$product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 );
print $product2->getSummaryLine();
print "\n";
?>

输出:

cd1 ( bobbleson, bob ): playing time - 50
book1 ( harrelson, harry ): page count - 30

点评:同样的结果,可以优化优化再优化。这里继承父类的方法。parent::getSummaryLine()。不过这个用的比较少。

继续添加一些有意思的内容

<?php
class ShopProduct {
  private $title;
  private $discount = 0;
  private $producerMainName;
  private $producerFirstName;
  protected $price;
  function __construct(  $title, $firstName,
              $mainName, $price ) {
    $this->title       = $title;
    $this->producerFirstName = $firstName;
    $this->producerMainName = $mainName;
    $this->price       = $price;
  }
  function setDiscount( $num ) {
    $this->discount=$num;
  }
  function getPrice() {
    return ($this->price - $this->discount);
  }
  function getProducer() {
    return "{$this->producerFirstName}".
        " {$this->producerMainName}";
  }
  function getSummaryLine() {
    $base = "{$this->title} ( {$this->producerMainName}, ";
    $base .= "{$this->producerFirstName} )";
    return $base;
  }
}
class CdProduct extends ShopProduct {
  public $playLength;
  function __construct(  $title, $firstName,
              $mainName, $price, $playLength ) {
    parent::__construct(  $title, $firstName,
                $mainName, $price );
    $this->playLength = $playLength;
  }
  function getPlayLength() {
    return $this->playLength;
  }
  function getSummaryLine() {
    $base = parent::getSummaryLine();
    $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 getPrice() {
    return $this->price;
  }
  function getNumberOfPages() {
    return $this->numPages;
  }
  function getSummaryLine() {
    $base = parent::getSummaryLine();
    $base .= ": page count - {$this->numPages}";
    return $base;
  }
}
$product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 );
$product1->setDiscount( 3 );
print $product1->getSummaryLine();
print "\n";
print "price: {$product1->getPrice()}\n";
$product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 );
$product2->setDiscount( 3 ); // 折扣对book无效
print $product2->getSummaryLine();
print "\n";
print "price: {$product2->getPrice()}\n";
?>

输出:

cd1 ( bobbleson, bob ): playing time - 50
price: 1
book1 ( harrelson, harry ): page count - 30
price: 4

点评:父类添加了折扣,book继承之后,修改了getPrice方法,所以折扣对book无效。

私有化属性,通过方法来设置与获取

<?php
class ShopProduct {
  // 私有化属性,通过方法来设置与获取
  private $title;
  private $producerMainName;
  private $producerFirstName;
  protected $price;
  private $discount = 0;
  public function __construct(  $title, $firstName,
              $mainName, $price ) {
    $this->title       = $title;
    $this->producerFirstName = $firstName;
    $this->producerMainName = $mainName;
    $this->price       = $price;
  }
  public function getProducerFirstName() {
    return $this->producerFirstName;
  }
  public function getProducerMainName() {
    return $this->producerMainName;
  }
  public function setDiscount( $num ) {
    $this->discount=$num;
  }
  public function getDiscount() {
    return $this->discount;
  }
  public function getTitle() {
    return $this->title;
  }
  public function getPrice() {
    return ($this->price - $this->discount);
  }
  public function getProducer() {
    return "{$this->producerFirstName}".
        " {$this->producerMainName}";
  }
  public function getSummaryLine() {
    $base = "{$this->title} ( {$this->producerMainName}, ";
    $base .= "{$this->producerFirstName} )";
    return $base;
  }
}
class CdProduct extends ShopProduct {
  private $playLength = 0;
  public function __construct(  $title, $firstName,
              $mainName, $price, $playLength ) {
    parent::__construct(  $title, $firstName,
                $mainName, $price );
    $this->playLength = $playLength;
  }
  public function getPlayLength() {
    return $this->playLength;
  }
  public function getSummaryLine() {
    $base = parent::getSummaryLine();
    $base .= ": playing time - {$this->playLength}";
    return $base;
  }
}
class BookProduct extends ShopProduct {
  private $numPages = 0;
  public function __construct(  $title, $firstName,
              $mainName, $price, $numPages ) {
    parent::__construct(  $title, $firstName,
                $mainName, $price );
    $this->numPages = $numPages;
  }
  public function getNumberOfPages() {
    return $this->numPages;
  }
  public function getSummaryLine() {
    $base = parent::getSummaryLine();
    $base .= ": page count - {$this->numPages}";
    return $base;
  }
  public function getPrice() {
    return $this->price;
  }
}
$product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 );
print $product1->getSummaryLine()."\n";
$product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 );
print $product2->getSummaryLine()."\n";
?>

输出:

cd1 ( bobbleson, bob ): playing time - 50
book1 ( harrelson, harry ): page count - 30

点评:这里进一步私有化了属性,要想获取只能通过方法。这样就确保了安全性。

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
使用数据库保存session的方法
Oct 09 PHP
关于访问控制的一首PHP面试题(对属性或方法的访问控制)
Sep 13 PHP
完美解决PHP中的Cannot modify header information 问题
Aug 12 PHP
PHP使用array_fill定义多维数组的方法
Mar 18 PHP
PHP数组操作类实例
Jul 11 PHP
php有效防止同一用户多次登录
Nov 19 PHP
使用php实现从身份证中提取生日
May 09 PHP
Laravel中日期时间处理包Carbon的简单使用
Sep 21 PHP
PHP迭代器接口Iterator用法分析
Dec 28 PHP
Laravel如何同时连接多个数据库详解
Aug 13 PHP
php日志函数error_log用法实例分析
Sep 23 PHP
浅谈laravel 5.6 安装 windows上使用composer的安装过程
Oct 18 PHP
PHP面向对象程序设计高级特性详解(接口,继承,抽象类,析构,克隆等)
Dec 02 #PHP
PHP面向对象程序设计之命名空间与自动加载类详解
Dec 02 #PHP
PHP面向对象程序设计之类与反射API详解
Dec 02 #PHP
PHP面向对象程序设计之对象生成方法详解
Dec 02 #PHP
PHP面向对象程序设计组合模式与装饰模式详解
Dec 02 #PHP
PHP与jquery实时显示网站在线人数实例详解
Dec 02 #PHP
谈谈php对接芝麻信用踩的坑
Dec 01 #PHP
You might like
fleaphp常用方法分页之Pager使用方法
2011/04/23 PHP
如何打开php的gd2库
2017/02/09 PHP
阿里对象存储OSS在laravel框架中的使用方法
2019/10/13 PHP
为JS扩展Array.prototype.indexOf引发的问题及解决办法
2015/01/21 Javascript
JS实现超炫网页烟花动画效果的方法
2015/03/02 Javascript
JavaScript对象学习小结
2015/09/02 Javascript
jQuery中bind(),live(),delegate(),on()绑定事件方法实例详解
2016/01/19 Javascript
JavaScript表单焦点自动切换代码
2016/07/24 Javascript
简洁实用的BootStrap jQuery手风琴插件
2016/08/31 Javascript
JS中append字符串包含onclick无效传递参数失败的解决方案
2016/12/26 Javascript
jQuery实现移动端Tab选项卡效果
2017/03/15 Javascript
详解webpack异步加载业务模块
2017/06/23 Javascript
实例讲解DataTables固定表格宽度(设置横向滚动条)
2017/07/11 Javascript
关于vue-router的beforeEach无限循环的问题解决
2017/09/09 Javascript
vue按需加载组件webpack require.ensure的方法
2017/12/13 Javascript
深入理解node.js http模块
2018/01/24 Javascript
Vue页面骨架屏的实现方法
2018/05/22 Javascript
vue实现多级菜单效果
2019/10/19 Javascript
Python中关键字is与==的区别简述
2014/07/31 Python
Python3实现将本地JSON大数据文件写入MySQL数据库的方法
2018/06/13 Python
python绘制热力图heatmap
2020/03/23 Python
详解python中的生成器、迭代器、闭包、装饰器
2019/08/22 Python
安装python3.7编译器后如何正确安装opnecv的方法详解
2020/06/16 Python
基于K.image_data_format() == 'channels_first' 的理解
2020/06/29 Python
django教程如何自学
2020/07/31 Python
html5 利用重力感应实现摇一摇换颜色可用来做抽奖等等
2014/05/07 HTML / CSS
颁奖典礼主持词
2014/03/25 职场文书
学期评语大全
2014/04/30 职场文书
机关作风建设剖析材料
2014/10/11 职场文书
2014年发展党员工作总结
2014/11/12 职场文书
工作表扬信范文
2015/01/17 职场文书
【HBU】数据库第四周 单表查询
2021/04/05 SQL Server
MySQL中你可能忽略的COLLATION实例详解
2021/05/12 MySQL
mysql的数据压缩性能对比详情
2021/11/07 MySQL
Android实现图片九宫格
2022/06/28 Java/Android
设置IIS Express并发数
2022/07/07 Servers