博主信息
博文 63
粉丝 1
评论 0
访问量 89596
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
类的继承和封装
桃儿的博客
原创
1106人浏览过

类的继承和封装

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举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学