[PHP] php类的继承和多态 →→→→→进入此内容的聊天室

来自 , 2021-03-27, 写在 PHP, 查看 118 次.
URL http://www.code666.cn/view/23fc4cba
  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
  4. <title>继承和多态</title>
  5. </head>
  6.  
  7. <body>
  8. <?php
  9. /*  父类  */
  10. class MyObject{
  11.         public $object_name;                                                                    //图书名称
  12.         public $object_price;                                                                           //图书价格
  13.         public $object_num;                                                                             //图书数量
  14.         public $object_agio;                                                                            //图书折扣
  15.         function __construct($name,$price,$num,$agio){                          //构造函数
  16.                 $this -> object_name = $name;
  17.                 $this -> object_price = $price;
  18.                 $this -> object_num = $num;
  19.                 $this -> object_agio = $agio;
  20.         }
  21.         function showMe(){                                                                              //输出函数
  22.                 echo '这句话不会显示。';
  23.         }
  24. }
  25. /*  子类Book  */
  26. class Book extends MyObject{                                                                    //MyObject的子类。
  27.         public $book_type;                                                                              //类别
  28.         function __construct($type,$num){                                                       //声明构造方法
  29.                 $this -> book_type = $type;
  30.                 $this -> object_num = $num;
  31.         }
  32.         function showMe(){                                                                              //重写父类中的showMe方法
  33.                 return '本次新进'.$this -> book_type.'图书'.$this->object_num.'本<br>';
  34.         }
  35. }
  36. /*  子类Elec  */
  37. class Elec extends MyObject{                                                                    //MyObject的另一个子类
  38.         function showMe(){                                                                              //重写父类中的showMe方法
  39.                 return '热卖图书:'.$this -> object_name.'<br>原价:'.$this -> object_price.'<br>特价:'.$this -> object_price * $this -> object_agio;
  40.         }
  41. }
  42. /*  实例化对象  */
  43. $c_book = new Book('计算机类',1000);                                                        //声明一个Book子类对象
  44. $h_elec = new Elec('PHP函数参考大全',98,3,0.8);                                   //声明一个Elec子类对象
  45. echo $c_book->showMe()."<br>";                                                          //输出Book子类的showMe()方法
  46. echo $h_elec->showMe();                                                                 //输出Elec子类的是showMe()方法
  47. ?>
  48. </body>
  49. </html>
  50.  

回复 "php类的继承和多态"

这儿你可以回复上面这条便签

captcha