類的多態
1.多態的介紹和優勢。
2.運算符:instanceof。
3.多態的簡單應用。
1.多態的介紹和優勢
介紹:多態性是繼承抽象和繼承后,面向對象語言的第三特征。
例子:USB接口,插上不同的東西會使用不同的功能。
優勢:OOP并不僅僅是把很多函數和功能集合起來,目的而是使用類,繼承,多態的方式描述我們生活中的一種情況。
2.運算符:instanceof
PHP一個類型運算符,用來測定一個給定的對象是否來自指定的對象
格式代碼如下:
- class A {}
- class B {}
- $thing = new A;
- if ($thing instanceof A) {
- echo "A";
- }
- if ($thing instanceof B) {
- echo "B";
- }
3.多態的簡單應用
實例1代碼如下:
- <?php
- class A {
- }
- class B {
- }
- $new = new A;
- if ($new instanceof A) {
- echo "A";
- }
- if ($new instanceof B) {
- echo "B";
- }
- ?>
實例2代碼如下:
- <?php
- interface MyUsb {
- function type();
- function alert();
- }
- class Zip implements MyUsb {
- function type() {
- echo "2.0";
- }
- function alert() {
- echo "U盤驅動正在檢測……<br />";
- }
- }
- class Mp3 implements MyUsb {
- function type() {
- echo "1.0";
- }
- function alert() {
- echo "MP3驅動正在檢測……";
- }
- }
- class MyPc {
- function Add_Usb($what) {
- $what->type();
- $what->alert();
- }
- }
- $p = new MyPc();
- $zip = new Zip();
- $mp3 = new Mp3();
- $p->Add_Usb($zip);
- $p->Add_Usb($mp3);
- ?>
補充一個實例代碼:
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
- <title>繼承和多態</title>
- </head>
- <body>
- <?php
- /* 父類 */
- class MyObject{
- public $object_name; //圖書名稱
- public $object_price; //圖書價格
- public $object_num; //圖書數量
- public $object_agio; //圖書折扣
- function __construct($name,$price,$num,$agio){ //構造函數
- $this -> object_name = $name;
- $this -> object_price = $price;
- $this -> object_num = $num;
- $this -> object_agio = $agio;
- }
- function showMe(){ //輸出函數
- echo '這句話不會顯示。';
- }
- }
- /* 子類Book */
- class Book extends MyObject{ //MyObject的子類。
- public $book_type; //類別
- function __construct($type,$num){ //聲明構造方法
- $this -> book_type = $type;
- $this -> object_num = $num;
- }
- function showMe(){ //重寫父類中的showMe方法
- return '本次新進'.$this -> book_type.'圖書'.$this->object_num.'本<br>';
- }
- }
- /* 子類Elec */
- class Elec extends MyObject{ //MyObject的另一個子類
- function showMe(){ //重寫父類中的showMe方法
- return '熱賣圖書:'.$this -> object_name.'<br>原價:'.$this -> object_price.'<br>特價:'.$this -> object_price * $this -> object_agio;
- }
- }
- /* 實例化對象 */
- $c_book = new Book('計算機類',1000); //聲明一個Book子類對象
- $h_elec = new Elec('PHP函數參考大全',98,3,0.8); //聲明一個Elec子類對象
- echo $c_book->showMe()."<br>"; //輸出Book子類的showMe()方法
- echo $h_elec->showMe(); //輸出Elec子類的是showMe()方法
- ?>
- </body>
- </html>
新聞熱點
疑難解答