【问题标题】:Get all functions in current plugin获取当前插件中的所有函数
【发布时间】:2014-03-19 12:42:29
【问题描述】:

有人知道如何获取当前插件中的所有功能吗?只有它声明的那些函数?

我知道函数get_defined_functions() 并尝试过,但这个函数获取所有函数的列表,但我只需要在当前插件中。 也许在WP中有可以获取插件中所有功能的功能?

当然我们可以通过以下方式获取函数的名称,但这不是最好的方式,因为我们的插件可以包含其他文件,而我无法获取它们的函数。

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

【问题讨论】:

  • 链接中的函数仅在当前文件中获取函数。当前文件可以包含许多其他文件!而且这个函数永远不会得到所有函数的数组。我用WP。它在安装时添加插件并拥有它的空间。我需要获取所有插件的功能列表,而不是它的一部分。
  • 是的,对不起,我误读了那部分:/ 我将撤回我的近距离投票;顺便说一句,赞成票是我的。该函数是解决方案的一部分,因为我得到了一个包含所有函数列表的数组:$arr = get_defined_functions_in_file( plugin_dir_path( __FILE__ ) ); var_dump ($arr);

标签: wordpress


【解决方案1】:

以下代码基于此问答:

这只是一个测试,它将在每个 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;
}

【讨论】:

  • 太棒了!对我来说就足够了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
相关资源
最近更新 更多