page34类的继承

好些时候没再写过面向对象了,现在忘了好多东西,经常不用所以忘记,没办法只能再重新看看了。只可惜在工作中不怎么用面向对象,不然也不能这样啊,以后在工作中还是不怎么用,以后又什么都不会了,如此恶性循环。。。

 1 <?php
 2 /**
 3  * Page34 Class Extends
 4  * @authors haidong (admin@zhe700.net)
 5  * @date    2015-03-25 10:13:29
 6  * @version $Id$
 7  */
 8 
 9 class Product{
10     public $title;
11     public $producerMainName;
12     public $producerFirstName;
13     public $price;
14     public function __construct($title,$producerMainName,$producerFirstName,$price){
15         $this->title = $title;
16         $this->producerMainName = $producerMainName;
17         $this->producerFirstName= $producerFirstName;
18         $this->price = $price;
19     } 
20     public function getProducer(){
21         return "{$this->producerFirstName}" . "{$this->producerMainName}";
22     }
23     public function getSummaryLine(){
24         $base = "{$this->title} ({$this->producerFirstName} {$this->producerMainName})";
25         return $base;
26     }
27 }
28 class CdProduct extends Product{
29     public $playLenth;
30     public function __construct($title,$producerMainName,$producerFirstName,$price,$playLenth){
31         parent::__construct($title,$producerMainName,$producerFirstName,$price);
32         $this->playLenth = $playLenth;
33     }
34     public function getSummaryLine(){
35         $base = "{$this->title} ({$this->producerFirstName} {$this->producerMainName})";
36         $base .= "play time ({$this->playLenth})";
37         return $base;
38     }
39 }
40 class BookProduct extends Product{
41     public $numPages;
42     public function __construct($title,$producerMainName,$producerFirstName,$price,$numPages){
43         parent::__construct($title,$producerMainName,$producerFirstName,$price);
44         $this->numPages = $numPages;
45     }
46     public function getSummaryLine(){
47         $base = parent::getSummaryLine();//只是对父类功能的丰富,前面功能 相同,直接调用就好了,没必要再重新写
48         $base .= "page numbers ({$this->numPages})";
49         return $base;
50     }
51 }
52 $cd = new CdProduct('CD','John','Smith',79,90);
53 echo $cd->getSummaryLine();
54 $book = new BookProduct('Book','Bob','zhang',49,360);
55 echo $book->getSummaryLine();

代码很简单,功能很简单。主要是想记住在子类丰富父类的时候,可以调用父类的构造函数进行初始化,不然的话,自己的数据是不完整的。还有就是对getSummaryLine只是对父类方法的丰富,所以没必要重新写,直接调用父类的方法就好了,就可以轻而易举的实现。以后写代码的时候还是需要好好考虑应该怎么把代码写的更优雅。过往匆匆里都是我的成长,我在此成长!

原文地址:https://www.cnblogs.com/haidong/p/4364979.html