PHP中public protected private的区别

public 表示全局,类内部外部子类都可以访问;

protected表示受保护的,只有本类或子类或父类中可以访问;

private表示私有的,只有本类内部可以使用;

<?php
// 父类
class father{
    public function a(){        //公有的
        echo 'aaaaa';        
    }
    protected function b(){     //受保护的
        echo 'bbbbb';
    }
    private function c(){       //私有的
        echo 'ccccc';
    }


}
//子类
class child extends father{
    function one(){
        parent::a();
    }
    function two(){
        parent::b();
    }
    function three(){
        parent::c();
    }
}


$father = new father();

$father->a();       //输出 public function a,结果是  aaaaa
$father->b();       //显示错误 外部无法调用受保护的方法
$father->c();       //显示错误 外部无法调用私有的方法

$child = new child();

$child->one();      //输出 public function a,结果是  aaaaa
$child->two();      //输出 public function b,结果是  bbbbb
$child->three();    //显示错误  无法调用父类private的方法 结果是: Call to private method father::c() from context 'child' 

   
原文地址:https://www.cnblogs.com/myzxh/p/10404784.html