2013-01-22 42 views
0

SO問題Weird behaviour with triggering __callStatic() from non-static method非常棒,因爲它解釋了__callStatic沒有從類本身中調用的奇怪行爲(請注意,我在5.3.3中看不到這種行爲,但是在5.3.8和5.3.12)。似乎__callStatic只能從類外部調用。現在這是事實。但是,如果我真的想在我的課堂內調用__callStatic,我該怎麼辦?我應該用什麼語法來解決這個問題?__callStatic方法的神祕行爲

+0

您可以包括測試情況? – Tchoupi

回答

2

它不必從課外,而不是從對象上下文(即其中$this是該課程的一個實例)。所以,你可以在一個靜態方法包裝這個調用,例如:

class TestCallStatic 
{ 
    public function __call($func, $args) 
    { 
     echo "__call($func)"; 
    } 

    public static function __callStatic($func, $args) 
    { 
     echo "__callStatic($func)"; 
    } 

    public function test() 
    { 
     self::_test(); 
    } 
    protected static function _test() 
    { 
     self::i_am_static(); 
    } 
} 

$test = new TestCallStatic(); 
$test->test(); 

輸出:

__callStatic(i_am_static)

+0

這是解決方案。這是要理解你想調用靜態函數的PHP解釋器。通過使用助手靜態函數_test,您可以避免模糊的調用。我的代碼唯一的區別是需要使用$ this,所以:self :: _ test($ this);和靜態函數_test($ myClassInstance) –

+0

我會嘗試將需要'$ this'的部分從不是的部分(僅將「static」部分移動到'_test') - 如果這對您的類是可能的。它使封裝更容易,代碼看起來更乾淨。 –

+0

5.3.3,5.3.8和5.3.12測試成功 –

0

您可以將功能抽象爲另一種方法,如Class :: magicCall($ method,$ args),並從__callStatic()中調用該方法。這樣,您也可以通過直接調用Class :: magicCall()來訪問該功能。