Get a PHP fully qualified class name from a file

Unfortunately, there is no ReflectionFile class, so you either have to assume the class name is the same as the file name, or you can tokenize the file & parse it for the class name.

You may also want to get traits. You can do that by modifying the if ($tokens[$i][0] === T_CLASS) line to use $tokens[$i][0] === T_CLASS || $tokens[$i][0] === T_TRAIT. I think the same works for T_INTERFACE, but I haven't confirmed.

Then you simply call $fullyQualifiedClassName = getClassFromFile($theFilePath);

function getClassFromFile($file){
        $fp = fopen($file, 'r');
        $class = $namespace = $buffer = '';
        $i = 0;
        while (!$class) {
            if (feof($fp)) break;

            $buffer .= fread($fp, 512);
            ob_start();
            $tokens = token_get_all($buffer);
            $err = ob_get_clean();
            // if (true&&strlen($err)>0){
                // echo $buffer;
                // echo $err."\n";
                // echo $class."\n";
                // echo "\n".$file;
                // print_r($tokens);
            // }
            if (strpos($buffer, '{') === false) continue;

            for (;$i<count($tokens);$i++) {
                if ($tokens[$i][0] === T_NAMESPACE) {
                    for ($j=$i+1;$j<count($tokens); $j++) {
                        if ($tokens[$j][0] === T_STRING) {
                            $namespace .= '\\'.$tokens[$j][1];
                        } else if ($tokens[$j] === '{' || $tokens[$j] === ';') {
                            break;
                        }
                    }
                }

                if ($tokens[$i][0] === T_CLASS) {
                    for ($j=$i+1;$j<count($tokens);$j++) {
                        if ($tokens[$j] === '{') {
                            $class = $tokens[$i+2][1];
                        }
                    }
                }
            }
        }
        if ($class=='')return '';
        return $namespace.'\\'.$class;
        
    }