2011-07-25 51 views
0

我有這個問題,我有很多巨大的功能,而且我在給定的腳本中只使用了很少的功能。每個函數都在它自己的文件中。當給定的函數不存在時,能夠'自動加載'或者更確切地說require_once是一件好事。'自動加載'功能在PHP?

也許有一種方法可以在腳本的開始處覆蓋Fatal error: Call to undefined function...,所以每當該錯誤觸發時,腳本首先會嘗試require_once一個名稱爲不存在的函數的文件名,然後嘗試調用該函數再次。

+0

相關:[功能自動加載器(2011年1月19日)](http://stackoverflow.com/questions/4737199/autoloader-for-functions) – hakre

回答

3

由於PHP 5.3.0你可以做些事情,如:

class Funcs 
{ 
    public function __callStatic($name, $args) { 
     if (!function_exists($name)) { 
      require_once sprintf(
       'funcs/%s.func.php', // generate the correct path here 
       $name 
      ); 
     } 

     if (function_exists($name)) { 
      return call_user_func_array($name, $args); 
     } 
     else { 
      // throw some error 
     } 
    } 
} 

,然後用它像(例如):

Funcs::helloworld(); 

這將嘗試加載一個文件funcs/helloworld.func.php後執行helloworld成功加載。

這樣你可以省略重複的內聯測試。

+0

一個很好的答案,就像我爲PHP提出的< 5.3在http://stackoverflow.com/questions/11352996/automatically-include-missing-functions :)我希望我看到這一點。 – tim

0

我想你可以嘗試寫一些錯誤處理,其中包括function_exists,但問題是確定何時加載功能?

您是否考慮過將函數集成到類中,以便您可以利用http://uk.php.net/autoload

1

如果你沒有腳本OOP,您可以使用功能存在功能:如果你 http://php.net/manual/en/function.function-exists.php

if(!function_exists('YOUR_FUNCTION_NAME')){ 
    //include the file 
    require_once('function.header.file.php'); 
} 

//現在調用cuntion

//參考正在使用類,例如。 OOP。比你可以使用__autoload方法:

function __autoload($YOUR_CUSTOM_CLASS){ 
    include $YOUR_CUSTOM_CLASS.'class.php'; 
} 

//現在你可以使用你還沒有包括班當前文件。

//參考: http://php.net/manual/en/language.oop5.autoload.php

0

function_exists不會幫助你趕上不存在的功能。相反,你將不得不用if(!function_exists())來包圍所有的函數調用。據我所知,您只能使用_autoload實現方式隨時隨地捕獲不存在的呼叫。也許將代碼放入類中或將相關函數集合放入一個文件並因此爲function_exists保存一些檢查是必需的?