2017年8月26日 星期六

PHP的get_called_class()

在以下例子中,我們可以使用get_called_class()來知道$result是用哪個Class的_test()函數生成的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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?



沒有留言:

張貼留言