Blogger Information
Blog 21
fans 0
comment 0
visits 28418
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP面向对象中private、protected和public的区别
a张张张浩的博客
Original
1110 people have browsed it

php中三种属性都不写默认是public

        private     protected       public
本类内     Y           Y              Y
子类内     N           Y              Y
外部       N           N              Y

上面显示的是调用关系,

public 表示全局,类内部外部子类都可以访问;
private表示私有的,只有本类内部可以使用;
protected表示受保护的,只有本类或子类或父类中可以访问;

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


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post