2014-03-19 23 views
1

有誰知道如何獲取當前插件中的所有功能?只有它宣佈的那些功能?獲取當前插件中的所有功能

我知道函數get_defined_functions()並試過了,但是這個函數得到了所有函數的列表,但我只需要在當前插件中。 也許在WP中有可以獲得插件中所有功能的功能嗎?

當然,我們可以通過以下方式獲取函數的名稱,但這不是最好的方法,因爲我們的插件可以包含其他文件,並且我無法獲得它們的功能。

$filename = __FILE__; 
$matches = array(); 
preg_match_all('/function\s+(\w*)\s*\(/', file_get_contents($filename), $matches); 
$matches = $matches[1]; 
+0

鏈接中的函數僅在當前文件中獲取函數。當前文件可以包含許多其他文件!而這個函數從來沒有得到所有函數的數組。我使用WP。當它們安裝並有空間時添加插件。我需要獲取所有插件的函數列表,而不是其中的一部分。 – Brotheryura

+0

是的,對不起,我誤讀了那部分內容:/我會收回我的近身投票; upvote是我的順便說一句。該函數是*解決方案的一部分,因爲我得到一個包含所有函數列表的數組:'$ arr = get_defined_functions_in_file(plugin_dir_path(__FILE__)); var_dump($ arr);' – brasofilo

回答

2

下面的代碼是基於這種問答& A的:

這只是一個試驗,將傾倒在每一頁WP所有PHP文件,它的功能(前部和後端)。代碼查找當前插件目錄中的所有PHP文件並搜索每個文件功能。

add_action('plugins_loaded', function() { 
    $path = plugin_dir_path(__FILE__); 
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); 
    foreach ($it as $file) { 
     $ext = pathinfo($file, PATHINFO_EXTENSION); 
     if('php' === $ext) { 
      echo "<br><br>".$file."<br>"; 
      $arr = get_defined_functions_in_file($file); 
      var_dump ($arr); 
     } 
    } 
}); 


/* From https://stackoverflow.com/a/2197870 */ 
function get_defined_functions_in_file($file) { 
    $source = file_get_contents($file); 
    $tokens = token_get_all($source); 

    $functions = array(); 
    $nextStringIsFunc = false; 
    $inClass = false; 
    $bracesCount = 0; 

    foreach($tokens as $token) { 
     switch($token[0]) { 
      case T_CLASS: 
       $inClass = true; 
       break; 
      case T_FUNCTION: 
       if(!$inClass) $nextStringIsFunc = true; 
       break; 

      case T_STRING: 
       if($nextStringIsFunc) { 
        $nextStringIsFunc = false; 
        $functions[] = $token[1]; 
       } 
       break; 

      // Anonymous functions 
      case '(': 
      case ';': 
       $nextStringIsFunc = false; 
       break; 

      // Exclude Classes 
      case '{': 
       if($inClass) $bracesCount++; 
       break; 

      case '}': 
       if($inClass) { 
        $bracesCount--; 
        if($bracesCount === 0) $inClass = false; 
       } 
       break; 
     } 
    } 

    return $functions; 
} 
+0

太好了!對我來說就夠了!謝謝! – Brotheryura

相關問題