class B extends A { public static function _test(){ return 'B_result'; } } class C extends A { public static function _test(){ return 'C_result'; } } class A { public static function test(){ $result = static::_test(); echo get_called_class(); echo $result; } } $sClass = 'C'; $sClass::test();output:
C
$result:C_result
雖然看似簡單,但是如果_test()算出來的結果不是那麼的規律,而且$sClass這邊又不是寫的這麼直觀。可以用get_called_class()來找到A::test()的static::_test()是呼叫哪個Class的_test()
參考資料:
https://stackoverflow.com/questions/506705/how-can-i-get-the-classname-from-a-static-call-in-an-extended-php-class How can I get the classname from a static call in an extended PHP class?
沒有留言:
張貼留言