首頁 >後端開發 >php教程 >PHP學習筆記5-類別的繼承/方法重寫

PHP學習筆記5-類別的繼承/方法重寫

WBOY
WBOY原創
2016-08-08 09:21:581303瀏覽

更改Man.php檔案名稱為People.php,加入程式碼:

<span>1</span><span>public</span><span>function</span><span> hi(){
</span><span>2</span><span>return</span><span>$this</span>->_name.' say hi'<span>;
</span><span>3</span> }

新檔案Man.php:

<span> 1</span> <?<span>php
</span><span> 2</span><span>/*</span><span>*
</span><span> 3</span><span> * Created by PhpStorm.
</span><span> 4</span><span> * User: Administrator
</span><span> 5</span><span> * Date: 2015/6/29
</span><span> 6</span><span> * Time: 11:18
</span><span> 7</span><span>*/</span><span> 8</span><span> 9</span><span>require_once</span> 'People.php'<span>;
</span><span>10</span><span>11</span><span>class</span> Man <span>extends</span> People{<span>//</span><span>extends:继承People类</span><span>12</span><span>public</span><span>function</span> __construct(<span>$age</span>,<span>$name</span><span>){
</span><span>13</span>         parent::__construct(<span>$age</span>,<span>$name</span>,'男'<span>);
</span><span>14</span><span>    }
</span><span>15</span><span>16</span><span>public</span><span>function</span> hi(){<span>//</span><span>重写People类的hi方法
</span><span>17</span><span>//        echo parent::hi();//保留父类hi方法</span><span>18</span><span>echo</span> 'Man '.<span>$this</span>->getName().' say hi'<span>;
</span><span>19</span><span>    }
</span><span>20</span> }

如果保留父類方法,可以這麼寫parent::hi();如果保留父類方法,可以這麼寫parent::hi();

這裡不保留,加入下面一行

修改index.php檔案:

<span>1</span><span>require_once</span> 'Man.php'<span>;
</span><span>2</span><span>$m</span> = <span>new</span> Man(10,'Vito'<span>);
</span><span>3</span><span>echo</span><span>$m</span>->hi();

最後在網頁上可以看到成功輸出的資訊:Man Vito say hi

以上就介紹了PHP學習筆記5-類別的繼承/方法重寫,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。 🎜 🎜 🎜
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn