PHP – 靜態屬性



PHP 中的“static”關鍵字用於在 PHP 類中定義靜態屬性和靜態方法。需要注意的是,static 關鍵字也用於定義靜態變數和靜態匿名函式。閱讀本章以瞭解 PHP 類中的靜態屬性。

在類定義中,使用 static 限定符宣告的變數成為其靜態屬性。static 關鍵字可以出現在訪問修飾符之前或之後。

static private $var1;
public static $var2;

如果要使用型別提示,則型別不能位於 static 關鍵字之前。

static private string $var1;
public static float $var2;

類中靜態屬性的值不能透過其物件(使用 -> 運算子)訪問。這樣做會導致一條通知,指出 以非靜態方式訪問靜態屬性 myclass::$var1。相反,靜態屬性是使用作用域解析運算子(由“::”符號表示)訪問的。

示例

檢視以下示例 -

<?php
   class myclass {
      static string $var1 = "My Class";
      function __construct() {
         echo "New object declared" . PHP_EOL;
      }
   }
   $obj = new myclass;
   echo "accessing static property with scope resolution operator: " . myclass::$var1 . PHP_EOL;
   echo "accessing static property with -> operator: ". $obj->var1 . PHP_EOL;
?>

它將產生以下 輸出 -

New object declared
accessing static property with scope resolution operator: My Class
PHP Notice:  Accessing static property myclass::$var1 as non static in hello.php on line 14

“self” 關鍵字

要從方法內部訪問靜態屬性,請使用 self 關鍵字引用當前類。在下面的示例中,類具有一個整數靜態屬性,每次宣告新物件時都會遞增。

<?php
   class myclass {
   
      /* Member variables */
      static int $var1 = 0;
      function __construct(){
         self::$var1++;
         echo "object number ". self::$var1 . PHP_EOL;
      }
   }
   for ($i=1; $i<=3; $i++) {
      $obj = new myclass;
   }
?>

它將產生以下 輸出 -

object number 1
object number 2
object number 3

“parent” 關鍵字

基類的靜態屬性可以透過在繼承類的函式內部引用基類(使用 parent 關鍵字)來使用。您需要使用“parent::static_property”語法。

示例

檢視以下示例 -

<?php
   class myclass {
   
      /* Member variables */
      static int $var1 = 0;
      function __construct() {
         self::$var1++;
         echo "object number ". self::$var1 . PHP_EOL;
      }
   }

   class newclass extends myclass{
      function getstatic() {
         echo "Static property in parent class: " . parent::$var1 . PHP_EOL;
      }
   }
   $obj = new newclass;
   $obj->getstatic();
?>

它將產生以下 輸出 -

object number 1
Static property in parent class: 1
廣告