2014-02-15 51 views
2
class A 
{ 
    public static function who1() 
    { 
     var_dump(get_called_class()); 
    } 
} 
class B extends A 
{ 
    public static function who2() 
    { 
     parent::who1(); 
    } 
} 
call_user_func(array('B', 'parent::who1')); 
B::who2(); 

我期待什麼:PHP類範圍與call_user_func混亂()

string 'B' (length=1) 

string 'B' (length=1) 

實際回報:

boolean false 

string 'B' (length=1) 

誰能告訴我,爲什麼輸出是跟我想象中有什麼不同?

還看到:

http://us1.php.net/manual/en/language.types.callable.php

http://us1.php.net/manual/en/function.get-called-class.php

編輯: 也許我以前的代碼不明確,這裏是新的例子:

class A 
{ 
    public static function who() 
    { 
     var_dump(get_called_class()); 
    } 
} 
class B extends A 
{ 
    public static function who() 
    { 
     echo 'hehe'; 
    } 
} 
call_user_func(array('B', 'parent::who')); 

爲什麼它輸出假?

+2

您不需要在調用「parent :: who1」時添加「父」部分。看看http://php.net/manual/en/language.oop5.inheritance.php:'例如,當你擴展一個類時,這個子類繼承了父類的所有公共和受保護的方法。除非一個類重寫這些方法,否則它們將保留它們的原始功能。' –

+0

不要使用'parent ::':'call_user_func(array('B','who1'));' – Wrikken

回答

2

PHP manual documentation for Object Inheritance

例如,當你擴展一個類,子類繼承所有的父類的公共和受保護的方法。除非一個類重寫這些方法,否則它們將保留它們的原始功能。

如上所述,存在call_user_func()無需parent前綴的有:

call_user_func(array('B', 'who')); 

你在一個類之外var_dump()因爲call_user_func()規定的方法調用了FALSE。所以get_called_class()表現如預期(或在手冊中提到):

如果從類的外部調用返回FALSE。

+0

我不明白。 get_called_class()仍然在方法who()中,who()在類A中。如果我把它叫做A :: who();它會輸出A. – nut

+0

@nut'get_called_class()'可能在這種情況下無法正確確定調用者類。這對我來說似乎是一個錯誤。看起來像'call_user_func(array('B','parent :: who'));'強制':: who()'在類作用域之外被調用。 – BlitZ

+1

是的,我的例子看起來很複雜,我會將它發佈到bug列表中以獲取詳細信息。並感謝提及對象繼承 – nut