PHP实战中知识总结 / 面向对象 - 访问权限

1、public: 公有类型

(1)在子类中可以通过self::var调用public方法或属性,parent::method调用父类方法

(2)在实例中可以能过$obj->var 来调用 public类型的方法或属性

2、protected: 受保护类型

(1)在子类中可以通过self::var调用protected方法或属性,parent::method调用父类方法

(2)在实例中不能通过$obj->var 来调用 protected类型的方法或属性

3、private: 私有类型

(1)该类型的属性或方法只能在该类中使用

(2)在该类的实例、子类中、子类的实例中都不能调用私有类型的属性和方法

<?php
//父类
class father{
  public function a(){
    echo "public function a".PHP_EOL;
  }
  private function b(){
    echo "private function b".PHP_EOL;
  }
  protected function c(){
    echo "protected function c".PHP_EOL;
  }
}
//子类
class child extends father{
  function d(){
    parent::a();//调用父类的a方法
  }
  function e(){
    parent::c(); //调用父类的c方法
  }
  function f(){
    parent::b(); //调用父类的b方法
  }
}
$father=new father();
$father->a(); //输出 public function a
$father->b(); //显示错误 外部无法调用私有的方法
$father->c(); //显示错误 外部无法调用受保护的方法
$chlid=new child();
$chlid->d();//输出 public function a
$chlid->e(); ////输出 protected function c
$chlid->f();//显示错误 无法调用父类private的方法 Uncaught Error: Call to private method father::b() from context 'child'

PHP实战中知识总结