Home > Backend Development > PHP Tutorial > PHP study notes 5-class inheritance/method rewriting, study notes 5-_PHP tutorial

PHP study notes 5-class inheritance/method rewriting, study notes 5-_PHP tutorial

WBOY
Release: 2016-07-13 09:48:20
Original
1483 people have browsed it

PHP study notes 5-class inheritance/method rewriting, study notes 5-

Change the name of the Man.php file to People.php, add the code:

<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> }
Copy after login

New file 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> }
Copy after login

If you want to retain the parent class method, you can write like this parent::hi();Do not retain it here, add the following line

Modify the index.php file:

<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();
Copy after login

Finally, you can see the successfully output information on the web page: Man Vito say hi

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1023841.htmlTechArticlePHP study notes 5-class inheritance/method rewriting, study notes 5-change the name of the Man.php file People.php, add code: 1 public function hi(){ 2 return $this -_name.' say hi' ; 3 } New...
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template