1. 程式人生 > >PHP常見概念混淆(五)之PHP類常量、靜態屬性和屬性的區別

PHP常見概念混淆(五)之PHP類常量、靜態屬性和屬性的區別

sta 支持 php5 中英文對照 ext static block 簡介 無法

最近在看手冊的時候發現PHP有好些個坑,一不註意就會掉進去,邊看邊將這些容易混淆的內容記載下來。

tips:看手冊的時候最好中英文對照著看,因為英文手冊上有好些個中文手冊沒有的東西(最新的PHP)

  1. PHP5.3 支持用一個變量調用類
  2. PHP5.6 支持用一個表達式賦值 PHP類常量PHP靜態屬性
  3. PHP7.1 支持對 PHP類常量 增加訪問控制

簡介

  • PHP類常量:定義方式和常量一樣
  • PHP屬性:定義方式和變量一樣
  • PHP靜態屬性:可PHP屬性的定義一樣,加了一個static

PHP屬性

  • 使用 -> 訪問的變量
  • 子類可以覆蓋父類的變量
  • 變量可以隨時修改
  • 在類中使用 $this
    訪問

PHP類常量

  • 使用 :: 訪問類常量,可以通過 對象 獲取類常量.

      <?php
    
      class test{
          const AAAA = "BBB";
      }
    
      $test = new test;
    
      echo test::AAAA;  //BBB
      echo $test::AAAA;   //BBB
  • 子類可以覆蓋父類的類常量

      <?php
    
      class test{
          const AAAA = "BBB";
      }
    
      class test2 extends test{
          const AAAA = "ccc";
    
          public function gettest(){
              return parent::AAAA;
          }
      }   
      $test = new test2;
    
      echo test::AAAA;   //ccc
      echo test2::AAAA;  //ccc
      echo $test::AAAA;  //BBB
      echo $test->gettest();  //BBB
  • 類常量一旦定義了無法修改
  • 在類中使用 self::類常量 訪問

PHP靜態屬性

  • 使用 :: 訪問靜態屬性,可以通過 對象 獲取靜態屬性.

     <?php
    
     class test{
         public static $AAAA = "BBB";
     }
    
    
     $test = new test;
    
     echo test::$AAAA;    //BBB
     echo $test::$AAAA;   //BBB
  • 子類可以覆蓋父類的靜態屬性

      <?php
    
      class test{
          public static $AAAA = "BBB";
      }
    
      class test2 extends test{
          public static $AAAA = "CCC";
      }
      $test = new test2;
    
      echo test2::$AAAA;   //CCC
      echo $test::$AAAA;   //CCC
  • 類常量定義了可以隨時進行修改
  • 再類中使用 self::$test 進行訪問

PHP常見概念混淆(五)之PHP類常量、靜態屬性和屬性的區別