博客列表 >类的继承和封装

类的继承和封装

桃儿的博客
桃儿的博客原创
2019年06月14日 17:39:30855浏览

类的继承和封装

public 公共属性

private 私有属性

proted  受保护的属性    


实例

<?php

class Students
{
    //属性
    //公共属性
    public $name;
    public $age;
    //private 私有属性
    //private $score;
    //受保护的属性
    protected $score;

    //构造方法
    public function __construct($name,$age,$score)
    {
        $this->name=$name;
        $this->age=$age;
        $this->score=$score;
        $this->getInfo();
    }
    //方法
    public function hobby($hobby)
    {
        return $hobby;
    }
    // 方法: 获取当前实例的属性,即学生的基本信息
    public  function  getInfo()
    {
        $res='学生的基本信息:'.'<br>';
        $res.='姓名:'.$this->name.'<br>';
        $res.='年龄:'.$this->age.'<br>';
        $res.='学习成绩: '.var_export($this->score,true).'<br>';
        $res.='爱好:'.$this->hobby('读书');
        echo $res;
    }
    // 为了方便外部访问, 通常会给私有属性创建一个获取器方法
    public function getScore()
    {
        return var_export($this->score, true);
    }
}
//类实例化
$student1=new Students('小明',10,['语文'=>80,'数学'=>70,'英语'=>60]);
//echo '<br>'.$student1->getScore();

echo '<hr>';

//扩展类
class Students1 extends Students
{
    public $role;
    public function __construct($name, $age, $score,$role)
    {
        $this->role=$role;
        parent::__construct($name, $age, $score);

    }
    public function getInfo()
    {
        $res='学生的基本信息:'.'<br>';
        $res.='姓名:'.$this->name.'<br>';
        $res.='年龄:'.$this->age.'<br>';
        //访问私有属性   $this->getScore();
        $res.='学习成绩: '.var_export($this->getScore(),true).'<br>';
        $res.='爱好:'.$this->hobby('读书').'<br>';
        $res.='角色:'.$this->role;
        echo $res;
    }
    //重写getScore()
    public function getScore()
    {
        if($this->role==='班长'){
            return var_export($this->score, true);
        }else{
            return '一般人不可见';
        }
    }
}
//类实例化
$student2=new Students1('小红',9,['语文'=>90,'数学'=>80,'英语'=>100],'学生');
echo '<hr>';
echo $student2->getScore();
echo '<hr>';
$student2->role='班长';
echo $student2->getScore();

运行实例 »

点击 "运行实例" 按钮查看在线实例


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议