批改状态:合格
老师批语:面向对象编程, 继承的概念非常重要的
<?php
namespace demo3;
class people{
public $name='张三';
public $sex='男';
//构造方法
//前面加了两个下划线的方法,又叫魔术方法
//魔术方法不需要用户手工调用,是由php根据某种条件自动触发
public function __construct($name,$sex){
$this->name=$name;
$this->sex=$sex;
//直接输出
echo $this->getInfo();
}
public function getInfo(){
//返回值后echo输出
return '名字:'.$this->name.',性别:'.$this->sex;
}
}
//echo (new people)->name.':'.(new people)->sex;
new people('小雷1','男1');
echo '<hr>';
//people父类,Sub1子类,子类集成父类的属性,使得代码复用,并且可以增加父类没有的属性.
class Sub1 extends people
{
//增加属性
public $score;
//构造方法
public function __construct($name,$sex,$score)
{
parent::__construct($name,$sex);
$this->score=$score;
}
public function getscore()
{
return $this->score;
}
}
//
$sub1=new Sub1('小雷2','男2','58');
echo '<hr>';
echo $sub1->getInfo();
echo '<hr>';
echo $sub1->name.'的性别是:'.$sub1->sex.',得分:'.$sub1->getscore();
echo '<hr>';
//子类
//方法重写
class Sub2 extends Sub1
{
//重写info()
public function getscore()
{
$getscore=parent::getscore();
switch(true)
{
case($getscore>90):
$result='优';
break;
case($getscore<=90&&$getscore>80):
$result='良';
break;
case($getscore<=80&&$getscore>70):
$result='中';
break;
case($getscore<=70&&$getscore>60):
$result='合格';
break;
default:
$result='不合格';
}
return $result;
}
}
$sub2=new Sub2('李四','男',67);
echo ',成绩:'.$sub2->getscore();
?>点击 "运行实例" 按钮查看在线实例

<?php
namespace _0930;
//public : 类中,类外,子类均可访问。
//protected: 类外,类中不可访问,子类中可访问。
//private: 只允许在类中访问, 类外与子类中不可访问。
class Demo4{
public $name;
protected $position;
private $salary;
public $department;
public function __construct($name,$position,$salary,$department){
$this->name=$name;
$this->position=$position;
$this->salary=$salary;
$this->department=$department;
}
//职位访问器/方法/函数
public function getPosition(){
return $this->position;
}
public function getSalary(){
return $this->salary;
}
}
$obj=new Demo4('朱老师','讲师',8888,'培训部');
echo $obj->name,'<br>';
echo $obj->getposition(),'<br>';
echo $obj->getSalary(),'<br>';
class Sub extends Demo4{
public function display(){
// return $this->name;
return $this->position;
// return $this->salary;
}
}
echo '<hr>';
$sub=new Sub('朱2老师','讲师',8888,'培训部');
echo $sub->display(),'<br>';点击 "运行实例" 按钮查看在线实例

总结:一、1.学了魔术方法:__construct,魔法方法不需要手工调用,会根据某种条件自动触发。
2.学了子函数:使用extends,子函数可以继承父函数的属性,函数...也可以添加属于自己的新属性。
3.学习了方法重写,可以在继承父函数的基础上对方法进行修改,parent::调用父类的构造函数。
4. public : 类中,类外,子类均可访问。protected: 类外,类中不可访问,子类中可访问。private: 只允许在类中访问, 类外与子类中不可访问。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号