PHP中private和public还有protected的区别

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

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

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

  1. <?
  2. //父类
  3. class father{
  4. public function a(){
  5. echo "function a";
  6. }
  7. private function b(){
  8. echo "function b";
  9. }
  10. protected function c(){
  11. echo "function c";
  12. }
  13. }
  14. //子类
  15. class child extends father{
  16. function d(){
  17. parent::a();//调用父类的a方法
  18. }
  19. function e(){
  20. parent::c(); //调用父类的c方法
  21. }
  22. function f(){
  23. parent::b(); //调用父类的b方法
  24. }
  25. }
  26. $father=new father();
  27. $father->a();
  28. $father->b(); //显示错误 外部无法调用私有的方法 Call to protected method father::b()
  29. $father->c(); //显示错误 外部无法调用受保护的方法Call to private method father::c()
  30. $chlid=new child();
  31. $chlid->d();
  32. $chlid->e();
  33. $chlid->f();//显示错误 无法调用父类private的方法 Call to private method father::b()
  34. ?>

复制代码

以上是自己对private和public还有protected 三者的个人理解。