zoukankan      html  css  js  c++  java
  • 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' 
    
       
  • 相关阅读:
    命令
    碎片知识
    驱动问题
    网络基础知识普及
    面向设计大作业——公司餐厅
    面向对象--购物车
    OO之接口-DAO模式代码阅读及应用
    有理数类的定义
    图知识点总结
    Java课程设计总结
  • 原文地址:https://www.cnblogs.com/myzxh/p/10404784.html
Copyright © 2011-2022 走看看