PHP – 類常量



PHP 允許在類中定義一個識別符號作為“類常量”,其值在每個類中保持不變。為了與類中的變數或屬性區分開來,常量的名稱前面不加通常的“$”符號,並使用“const”限定符定義。需要注意的是,PHP 程式也可以使用define()函式建立全域性常量。

常量的預設可見性為 public,儘管在定義中可以使用其他修飾符。常量的值必須是一個表示式,而不是一個變數,也不是一個函式呼叫/屬性。常量的值可以透過類名使用作用域解析運算子來訪問。然而,在方法內部,它可以透過self變數來引用。

class SomeClass {
   const CONSTANT = 'constant value';
}
echo SomeClass::CONSTANT;

常量名稱區分大小寫。按照慣例,常量名稱使用大寫字母。

示例

此示例演示如何定義和訪問類常量:

<?php
   class square {
      const PI=M_PI;
      var $side=5;
      function area() {
         $area=$this->side**2*self::PI;
         return $area;
      }
   }
   $s1=new square();
   echo "PI=". square::PI . "\n";
   echo "area=" . $s1->area();
?>

它將產生以下輸出

PI=3.1415926535898
area=78.539816339745

類常量作為表示式

在此示例中,類常量被賦予一個表示式:

<?php
   const X = 22;
   const Y=7;

   class square {
      const PI=X/Y;
      var $side=5;
      function area() {
         $area=$this->side**2*self::PI;
         return $area;
      }
   }
   $s1=new square();
   echo "PI=". square::PI . "\n";
   echo "area=" . $s1->area();
?>

它將產生以下輸出

PI=3.1428571428571
area=78.571428571429

類常量可見性修飾符

請看以下示例:

<?php
   class example {
      const X=10;
      private const Y=20;
   }
   $s1=new example();
   echo "public=". example::X. "\n";
   echo "private=" . $s1->Y ."\n";
   echo "private=" . example::Y ."\n";
?>

它將產生以下輸出

public=10
PHP Notice:  Undefined property: example::$Y in  line 11

private=
PHP Fatal error:  Uncaught Error: Cannot access private const example::Y
廣告