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 三者的個人理解。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM