php继承

将公共的部分写在父类中,将特例写在子类中

class ShopProduct{      // 父类
    private $title = 'default product';
    private $producerMainName = 'main name';
    private $producerFirstName = 'first name';
    protected $price = 0;

    public function __construct($title,$producerMainName,$producerFirstName,$price){
        $this->title = $title;
        $this->producerMainName = $producerMainName;
        $this->producerFirstName = $producerFirstName;
        $this->price = $price;
    }

    /**
     * @return string 作者
     */
    public function getProducer(){
        return $this->producerMainName . $this->producerFirstName;
    }

    public function getSummaryLine(){
        $base = "$this->title :($this->producerMainName"."$this->producerFirstName)";
        return $base;
    }

}

class CdProduct extends ShopProduct{    // 子类可以继承和修改父类的功能,默认继承所有的public和protected方法(但是没有继承private方法)
    private $playLength;     // 父类的拓展属性

    function __construct($title,$producerMainName,$producerFirstName,$price,$playLength){
        parent::__construct($title,$producerMainName,$producerFirstName,$price);    // 引用类的途径 :句柄(handle) ,parent关键字,引用类而不是对象时使用 ::
        $this->playLength = $playLength;
    }

    /**
     * @return mixed 播放时间
     */
    function getPlayLength(){
        return $this->playLength;
    }

    /**
     * @return string 唱片的标题,作者,价格和播放时间
     */
    function getSummaryLine(){
        $base = parent::getSummaryLine();   // 子类需要在设置自己的属性前调用父类的构造方法
        $base .= ": playing time - $this->playLength";
        return $base;
    }
}

class BookProduct extends ShopProduct{
    private $numPages;

    function __construct($title,$producerMainName,$producerFirstName,$price,$numPages){
        parent::__construct($title,$producerMainName,$producerFirstName,$price);
        $this->numPages = $numPages;
    }

    /**
     * @return mixed 书籍的页数
     */
    function getNumberOfPages(){
        return $this -> numPages;
    }

    /**
     * @return string 书籍的标题,作者,价钱和页数信息
     */
    function getSummaryLine(){
        $base = parent::getSummaryLine();
        $base .= ": page count - $this->numPages";
        return $base;
    }

}

$cd = new CdProduct('唱片','周','杰伦',100,180);
$book = new BookProduct('书籍','鲁','迅',58,300);
print $cd->getSummaryLine().'</br>';    // 唱片 :(周杰伦): playing time - 180
print $book->getSummaryLine();          // 书籍 :(鲁迅): page count - 300

 

posted @ 2017-02-13 16:13  Chrdai  阅读(286)  评论(0编辑  收藏  举报