确定在 PHP 类文件中定义了哪些类 [英] Determining what classes are defined in a PHP class file

查看:23
本文介绍了确定在 PHP 类文件中定义了哪些类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我们项目中的每个 PHP 文件都包含一个类定义,我如何确定文件中定义了哪些类?

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?

我知道我可以只对 class 语句的文件进行正则表达式,但我更愿意做一些更有效的事情.

I know I could just regex the file for class statements, but I'd prefer to do something that's more efficient.

推荐答案

我正在做的一个项目需要这样的东西,这里是我写的函数:

I needed something like this for a project I am working on, and here are the functions I wrote:

function file_get_php_classes($filepath) {
  $php_code = file_get_contents($filepath);
  $classes = get_php_classes($php_code);
  return $classes;
}

function get_php_classes($php_code) {
  $classes = 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];
        $classes[] = $class_name;
    }
  }
  return $classes;
}

这篇关于确定在 PHP 类文件中定义了哪些类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆