2011-07-21 31 views
5

如果呼叫在類未定義的方法制作,魔術方法__call可以攔截電話,這樣我就可以處理這種情況,我認爲合適的: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods是否有像php中的全局範圍魔術方法__call()函數?

有沒有在PHP,從而提供任何機制我可以用全球範圍內的功能做同樣的事情。 點最好用的代碼所示:

<?php 
    function return_some_array(){ 
     $a = array(); 
     //Do stuff to array 
     return array(); 
    } 

    // Now i call the function like so: 
    $give_me_array = return_some_array(); 

    // But sometimes I want the array to not contain zeroes, nulls etc. 
    // so I call: 
    $give_me_array_filtered = return_some_array_filtered(); 

    // But i haven't defined return_some_array_filtered() anywhere. 
    // Instead I would like to do something like so: 
    function __magic_call($function_name_passed_automatically){ 
     preg_match('/(.*)_filtered$/', $function_name_passed_automatically, $matches); 
     $function_name_that_i_defined_earlier_called_return_some_array = $matches[1]; 
     if($matches){ 
     $result = call_user_func($function_name_that_i_defined_earlier_called_return_some_array); 
     $filtered = array_filter($result); 
     return $filtered; 
     } 
    } 

    //So now, I could call return_some_other_array_filtered() and it would work provided I had defined return_some_other_array(). 
    //Or even Donkey_filtered() would work, provided I had defined Donkey() somewhere. 
    ?> 

這是在所有可能的?

回答

1

不一樣。

如果您製作了一個類似return_some_array_filtered :: go()的靜態方法,那麼您可以使用PHP5的autoload()工具來動態創建類和方法。創建之後,通話將照常進行。您可能需要在該課程上實施callStatic()。謹防動態創建一個從頭開始的類(不包括include())在PHP中是不平凡的。

+0

謝謝!我想我會試試看。 –

+0

@ V-A這當然是相當浪費和不必要的瑣碎事情。你應該像平常一樣定義和調用你的函數。 – deceze

+0

另一個說明:你認爲這可以作爲一個擴展來實現嗎?我會想象它會相當簡單? –