温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在子类中重载父类的方法(重写方法)

发布时间:2020-06-04 22:08:54 来源:网络 阅读:637 作者:yuxin1234567890 栏目:网络安全

<?php

class person{

protected $name;

protected $sex;

protected $age;


function __construct($name,$sex,$age){

$this->name=$name;

$this->sex=$sex;

$this->age=$age;

}


function say(){

echo "我的名字:".$this->name.";性别:".$this->sex.";年龄:".$this->age."。<br/>";

}

}


class student extends person{

private $school;


//覆盖父类中的构造方法,在参数列表中多参加一个学校属性,用来创建对象并初始化成员属性

function __construct($name="",$sex="",$age="",$school=""){

$this->name=$name;

$this->sex=$sex;

$this->age=$age;

$this->school=$school;

}


function study(){

echo $this->name."正在".$this->school."学习。<br/>";

}


//定义一个和父类中同名的方法,将父类中的说话方法覆盖并重写,多说出所在的学校名称

function say(){

echo "我的名字:".$this->name.";性别:".$this->sex.";年龄:".$this->age.";在".$this->school."上学。<br/>";

}


}


$student1=new student("张三","男","20","一中");

$student1->study();

$student1->say();

?>

代码运行结果是:

在子类中重载父类的方法(重写方法)


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI