类成员的访问限制与封装技术小结

原创 2019-01-06 17:39:58 256
摘要:class Boss {     public $name;     protected $dept;     private $salary;     //构造方法   &
class Boss
{
    public $name;

    protected $dept;

    private $salary;

    //构造方法
    public function __construct($name,$dept,$salary)
    {
        $this->name = $name;
        $this->dept = $dept;
        $this->salary = $salary;
    }

    public function getSalary()
    {

        $res = $this->salary;
        if ($this->name == '小明') {
            $res = '该员工在国家地下部门工作!工资保密';
        }
        return $res;
    }

    public function getDept()
    {
        $res = $this->dept;
        if ($this->dept == '司法部') {
            $res = '老板的小蜜你都敢查?想把牢底坐穿吗';
        }
        return $res;
    }
}

$boss = new Boss('小明','司法部',500);
echo '姓名:', $boss->name, '<br>';
echo '部门:', $boss->getDept(), '<br>';
echo '工资:', $boss->getSalary(), '<br>';

public: 公开,在类的内部,外部都可以访问

protected: 受保护,仅在类的内部,以及子类中的访问(子类下节课讲)

private: 私有,仅在本类内部访问,外部以及子类均不能访问

 * 封装的概念

 * 1. 类属性,除非必要,否则都应该声明为私有或受保护的,屏蔽外部直接访问

 * 2. 为类成员属性提供访问访问接口,在接口方法中对外部访问进行过滤,保护数据

如上代码痛过封装getDept()和getSalary()两个·方法实现对用户输入的信息进行有条件的筛选显示

批改老师:灭绝师太批改时间:2019-01-06 17:40:57
老师总结:完成的不错,在作业中嵌入笔记是个很好的习惯!

发布手记

热门词条