2015-02-09 51 views
0

在下面的PHP代碼中,我想用Foo類中的__CLASS__魔術常數替換爲函數__X__()(或類似的東西),以便當方法hello()Bar類的實例$bar中調用,它打印hello from Bar(而不是hello from Foo)。我想要 而不是重寫hello()裏面的Bar在運行時而不是在編譯時綁定的__CLASS__的版本

所以基本上,我想要一個__CLASS__的版本在運行時而不是在編譯時動態綁定。

class Foo { 

    public function hello() { 

    echo "hello from " . __CLASS__ . "\n"; 

    } 

} 

class Bar extends Foo { 

    public function world() { 

    echo "world from " . __CLASS__ . "\n"; 

    } 

} 

$bar = new Bar(); 
$bar->hello(); 
$bar->world(); 

OUTPUT:

hello from Foo 
world from Bar 

我希望這個輸出(未覆蓋hello()Bar):

hello from Bar 
world from Bar 

回答

2

,你可以簡單的使用get_class(),就像這樣:

echo "hello from " . get_class($this) . "\n"; 
echo "world from " . get_class($this) . "\n"; 

輸出:

hello from Bar 
world from Bar 
+0

@JohnSonderson不客氣!祝你有美好的一天:D – Rizier123 2015-02-09 01:38:43

+0

這是一個很好的答案。謝謝。 :-) – 2015-02-09 01:39:26

相關問題