PHP中的延遲靜態繫結是什麼?


延遲靜態繫結的基本思想是,繼承概念和“self”關鍵字的概念不遵循相同的規則。例如,在子類中呼叫的父類中的方法“fun”不會使“self”指向子類(如預期的那樣)。

延遲靜態繫結的概念引入了新的關鍵字“static”,使用該關鍵字時,它會將函式繫結到執行時類,或首次使用函式的類。除此之外,任何 static 函式或變數通常在執行時執行,而不是在編譯時執行。因此,如果需要將值動態分配給 static 的變數,則發生在執行時,這稱為延遲靜態繫結。

示例

 線上演示

<?php
class student
{
   public static $my_name = 'Joe';
   public static function getName()
   {
      return "The name of the student is : " . self::$my_name;
   }
   public static function getAge()
   {
      echo static::getName();
   }
}
class Professor extends student
{
   public static function getName()
   {
      return "The name of the student is : " . self::$my_name . " and age is 24.";
   }
}
student::getAge();
echo "
"; Professor::getAge(); ?>

輸出

The name of the student is : Joe
The name of the student is : Joe and age is 24.

名為“student”的類包含一個名稱和一個用於獲取名稱的函式。另一個函式獲取學生的年齡。名為“professor”的類擴充套件了“student”類,並且還繼承了該函式。對 student 和 professor 的例項呼叫獲取年齡的函式。

更新時間: 01-Jul-2020

1 千 + 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告