如何获取PHP类文件中声明的所有use语句 [英] How to get all use statements declared in PHP class file

查看:583
本文介绍了如何获取PHP类文件中声明的所有use语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有以下课程:

Lets say I have a following class:

<?php
namespace ImTheVendor\Project5;

use ImTheVendor\Project1\SomeClass,
    ImTheVendor\Project2\SomeOtherClass;
use ImTheVendor\Project5\SomeClass;

class Something
{

}

如何获取所有使用use声明的名称空间?我需要对文件本身进行正则表达式还是有更简单的方法?

How can I get all namespaces declared with use statement? Do I have to regexp the file itself or is there an easier way to do it?

推荐答案

我将使用TokenFinderTool :: getUseDependencies方法.

I would use the TokenFinderTool::getUseDependencies method.

$f = $modulesDir . "/Bat/FileSystemTool.php";
$tokens = token_get_all(file_get_contents($f));
$dependencies = TokenFinderTool::getUseDependencies($tokens);

此外,它还有一种在给定目录中查找所有使用语句"的方法:

Also, it has a method that find all "use statements" inside a given directory:

$dir = $modulesDir . "/Bat";
$deps = TokenFinderTool::getUseDependenciesByFolder($dir);

可以在此处找到一个工作示例: https://github.com/lingtalfi/TokenFun#tokenfindertool

A working example can be found here: https://github.com/lingtalfi/TokenFun#tokenfindertool

此外,本文中还介绍了另一种解决方案: 最简单的方法来检测/删除未使用的`use` PHP代码库中的语句

Also, there is another solution described in this post: Easiest way to detect/remove unused `use` statements from PHP codebase

这篇关于如何获取PHP类文件中声明的所有use语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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