Blogger Information
Blog 63
fans 1
comment 0
visits 76027
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类的继承和封装
桃儿的博客
Original
860 people have browsed it

类的继承和封装

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();

运行实例 »

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


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post