2012-10-22 60 views
0

我不明白這個晚期的靜態綁定是如何工作的。這是正常的嗎?

abstract class A{ 

    final public static function doprint(){ 
    print get_called_class() . '<br>'; 
    } 


    public static function wrapper(){ 
    self::doprint(); 
    static::doprint(); 
    } 

} 

class A2 extends A{}  

A2::wrapper(); 

get_called_class()在兩種情況下打印A2,即使當我使用self調用doprint方法時也是如此。爲什麼?

回答

1

get_called_class()總是返回實際調用的類。你打電話A2 ::所以它是A2。

在我的網站上有一個教程,其中有一個LSB單例抽象類。我沒有鏈接到這裏,因爲總是有殭屍警惕,並且甚至沒有看到鏈接就刪除鏈接。 但這是在我的描述。

LSB的問題在於A中的方法可以調用B中的方法,它可以調用A中的方法。 參見這個例子:

header('Content-Type: text/plain'); // Pretty text output 
// LSB Parent 
class A { 
    // NOLSB: Will call Current Class method 
    static public function TriggerSelf() { 
     self::OverrideMe(); 
    } 
    // LSB: Will call Inheriting Class method (or Current if none Inherits) 
    static public function TriggerStatic() { 
     static::OverrideMe(); 
    } 
    // Method to Override 
    static public function OverrideMe() { 
     echo 'A here', PHP_EOL; 
    } 
} 

// LSB Child 
class B extends A { 
    // Override by LSB 
    static public function OverrideMe() { 
     echo 'B here', PHP_EOL; 
    } 
} 

A::TriggerSelf(); // <- NO LSB 
A::TriggerStatic(); // <- LSB (but not inheritance) 

B::TriggerSelf(); // <- NO LSB 
B::TriggerStatic(); // <- LSB (with inheritance, so it works) 

參見B :: TriggerStatic如何()可以使A調用而B :: TriggerSelf(A B法)調用的方法。 這就是LSB。父類靜態方法可以調用子類靜態方法。這幾乎是靜態的摘要:)

研究示例,它會有道理。

1

我認爲get_called_class()告訴你哪個類被調用,它的輸出是正確的。

延遲靜態綁定允許self上下文冒泡,因此定義更高的方法可以對被調用方法的對象進行操作。

相關問題