权限修饰符public,private,protected的区别及示例。
- public:公有的,可以在类,子类及类的外部使用;
- private:私有的,只能在类中使用,不能在子类及类的外部使用;
- protected:受保护的,可以在类及子类中使用,不能在类的外部使用;
如下图:
| 类 | 子类 | 外部 | |
| public | √ | √ | √ |
| private | √ | ||
| protected | √ | √ |
示例:
1.public
<?php class classFather{ public function test(){ echo "我是父类中的成员方法;" } class son extends classFather{ } $son =new son(); $son->test(); ?>
运行结果:
我是父类中的成员方法;
2.private:
<?php class classFather{ private function test(){ echo "我是父类中的成品方法;" } class son extends classFather{ } $son =new son(); $son->test(); ?>
运行结果:
Fatal error: Uncaught Error: Call to protected method Website::demo() from context '' ··· ···
程序报错并停止运行;
3.protected:
<?php class classFather{ protected function test(){ echo "我是父类中的成员方法;" } class son extends classFather{
public function test1(){
$this->test(); } $son =new son(); $son->test1(); ?>
运行结果:
我是父类中的成员方法;
浙公网安备 33010602011771号