例子
namespace Foo;
use Test\One;
use Test\Two;
use Test\Three;
class Sample
{}
如何将别名(USE)作为数组获取?我希望得到的例子
$test = [测试\一,测试\二,测试\树];
有人在不扫描文件的情况下有什么建议吗?
或者是否有一个 PHP 函数可以将列表别名作为数组返回?
任何帮助将不胜感激。
最佳答案
假设我有以下类并且文件位于并命名为以下文件名和位置 src/Foo.php
namespace Foo;
use Test\One;
use Test\Two;
use Test\Three;
class Sample
{}
现在我可以扫描这个文件使用此功能,我可以扫描该类并获得预期的结果。
<?php
use \SplFileObject;
class Scanner
{
public static function getUseAliases()
{
$className = new SplFileObject("src/Foo.php");
$use = [];
while (!$className->eof())
{
$alias = explode("use ", $className->fgets());
if(!empty($alias[1]))
{
$use[] = trim($alias[1]);
}
}
$className = null; //Unset the file to prevent memory leaks
print_r($use);//will print my expected output [Test\One, Test\Two, Test\Three]
}
}
我认为应该有更好的方法来获得相同的结果,这就是我发布当前解决方案的原因。请让我知道你的想法。
关于php - 是否可以将 php 中的类别名列表作为数组获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64053226/