<?php
/*
?* WEB开发笔记 www.chhua.com 每日练习之访问方法 public private protected的封装
?*/
class Product {//基类
?private? $name;
?private $type;
?protected $jige;
?
?public function __construct($name,$type,$jage){
??$this->name=$name;
??$this->type=$type;
??$this->jige=$jage;
?}
?
?public function getName(){//访问方法
??return $this->name;
?}
?public function getType(){
??return $this->type;
?}
?public function getJiage(){
??return $this->jige;
?}
?
?public function get_zhaiyao(){
??$zhaiyao=$this->name.”({$this->type})<br>价格:{$this->jige}<br>”;
??return $zhaiyao;
?}
}

class BookProduct extends Product {//继承基类
?private $numpages;
?
??? public function __construct($name,$type,$jige,$numpages=0){
??parent::__construct($name,$type,$jige);//访问父类的方法
??$this->numpages=$numpages;
?}
?public function getPages(){//独有方法
??return $this->numpages;
?}
?
?public function get_zhaiyao(){//重载方法
??$zhaiyao=parent::get_zhaiyao();//调用父类的方法
??$zhaiyao.=”Page Count-{$this->numpages}页”;
??return $zhaiyao;
?}
}

class CdProduct extends Product{//继承基类
?private $playlength;
?
public function __construct($name,$type,$jiage,$playlength=0){
??parent::__construct($name,$type,$jiage);
??$this->playlength=$playlength;
?}
?public function getTimes (){//独有方法
??return $this->playlength;
?}
?
?public function get_zhaiyao(){//重载方法
??$zhaiyao=parent::get_zhaiyao();//调用父类的方法
??$zhaiyao.=”Play Length-{$this->playlength}分”;
??return $zhaiyao;
?}
}

$cd=new CdProduct(“《经典教程》”,”CD”,58.8,120);

$book=new BookProduct(“《php教程》”,”BOOK”,98.8,456);

echo $cd->get_zhaiyao();
echo “<br>”;
echo $book->get_zhaiyao();
/*把类的属性进行封装,靠访问方法来实现属性的调用,提高类的安全性*/
?>

自由转载,转载请注明: 转载自WEB开发笔记 www.chhua.com

本文链接地址: PHP类的访问方法 public private protected的封装 http://www.chhua.com/web-note726

相关笔记

更多