PHP 延遲靜態繫結


簡介

PHP 中的延遲靜態繫結功能用於在靜態繼承中引用被呼叫的類。當呼叫靜態方法時,類名與作用域解析運算子 (::) 一起使用,而在其他例項方法的情況下,我們使用物件名來呼叫它們。static:: 不會使用定義方法的類來解析,而是使用執行時資訊計算。對當前類的靜態引用使用函式所屬的類來解析,而不是它被定義的位置。

示例

在以下程式碼中,父類使用 self:: 字首呼叫靜態方法。當使用子類呼叫相同的方法時,它不會引用子類名,因為它沒有被解析。

示例

 線上演示

<?php
class test1{
   public static $name="Raja";
   public static function name(){
      echo "name of class :" . __CLASS__;
   }
   public static function getname(){
      self::name();
   }
}
class test2 extends test1{
   public static function name(){
      echo "name of class :" . __CLASS__;
   }
}
test2::getname();
?>

輸出

結果顯示,與預期相反,返回了父類名。

name of class :test1

使用 static:: 代替 self:: 會在執行時建立延遲繫結。

示例

 線上演示

<?php
class test1{
   public static function name(){
      echo "name of class :" . __CLASS__;
   }
   public static function getname(){
      static::name();
   }
}
class test2 extends test1{
   public static function name(){
      echo "name of class :" . __CLASS__;
   }
}
test2::getname();
?>

上面的程式碼現在按預期返回子類名。

輸出

name of class :test2

在非靜態上下文中使用 static::

父類中的私有方法被複制到子類,因此它的作用域仍然是父類。

示例

 線上演示

<?php
class test1{
   private function name(){
      echo "name of class :" . __CLASS__ ."
";    }    public function getname(){       $this->name();       static::name();    } } class test2 extends test1{    // } $t2=new test2(); $t2->getname(); ?>

輸出

輸出顯示以下結果

name of class :test1
name of class :test1

但是,當覆蓋父方法時,其作用域會發生變化。

示例

class test3 extends test1{
   private function name() {
      /* original method is replaced; the scope of name is test3 */
   }
}
$t3 = new test3();
$t3->name();

輸出

輸出顯示以下異常

PHP Fatal error: Uncaught Error: Call to private method test3::name() from context ''

更新於: 2020-09-18

209 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告