Determining what classes are defined in a PHP class file

后端 未结 8 1315
-上瘾入骨i
-上瘾入骨i 2020-11-27 14:56

Given that each PHP file in our project contains a single class definition, how can I determine what class or classes are defined within the file?

I know I could jus

相关标签:
8条回答
  • 2020-11-27 15:19

    Use PHP's function get_declared_classes(). This returns an array of classes defined in the current script.

    0 讨论(0)
  • 2020-11-27 15:24

    I've extended Venkat D's answer a bit to include returning the methods, and to search through a directory. (This specific example is built for CodeIgniter, which will return all the methods in the ./system/application/controller files - in other words, every public url that you can call through the system.)

    function file_get_php_classes($filepath,$onlypublic=true) {
        $php_code = file_get_contents($filepath);
        $classes = get_php_classes($php_code,$onlypublic);
        return $classes;
    }
    
    function get_php_classes($php_code,$onlypublic) {
        $classes = array();
        $methods=array();
        $tokens = token_get_all($php_code);
        $count = count($tokens);
        for ($i = 2; $i < $count; $i++) {
            if ($tokens[$i - 2][0] == T_CLASS
            && $tokens[$i - 1][0] == T_WHITESPACE
            && $tokens[$i][0] == T_STRING) {
                $class_name = $tokens[$i][1];
                $methods[$class_name] = array();
            }
            if ($tokens[$i - 2][0] == T_FUNCTION
            && $tokens[$i - 1][0] == T_WHITESPACE
            && $tokens[$i][0] == T_STRING) {
                if ($onlypublic) {
                    if ( !in_array($tokens[$i-4][0],array(T_PROTECTED, T_PRIVATE))) {
                        $method_name = $tokens[$i][1];
                        $methods[$class_name][] = $method_name;
                    }
                } else {
                    $method_name = $tokens[$i][1];
                    $methods[$class_name][] = $method_name;
                }
            }
        }
        return $methods;
    }
    
    function mapSystemClasses($controllerdir="./system/application/controllers/",$onlypublic=true) {
        $result=array();
        $dh=opendir($controllerdir);
        while (($file = readdir($dh)) !== false) {
            if (substr($file,0,1)!=".") {
                if (filetype($controllerdir.$file)=="file") {
                    $classes=file_get_php_classes($controllerdir.$file,$onlypublic);
                    foreach($classes as $class=>$method) {
                        $result[]=array("file"=>$controllerdir.$file,"class"=>$class,"method"=>$method);
    
                    }
                } else {
                    $result=array_merge($result,mapSystemClasses($controllerdir.$file."/",$onlypublic));
                }
            }
        }
        closedir($dh);
        return $result;
    }
    
    0 讨论(0)
提交回复
热议问题