简体   繁体   English

是否可以将php中的类别名列表作为数组获取?

[英]Is it possible to get the list of the class alias in php as array?

example例子

namespace Foo;
use Test\One;
use Test\Two;
use Test\Three;

class Sample
{}

How can I get the aliases (USE) as an array?如何将别名(USE)作为数组获取?

example of what I am looking to get我希望得到的例子

$test = [Test\\One, Test\\Two, Test\\Tree]; $test = [测试\\一,测试\\二,测试\\树];

Does anybody have any suggestions without scanning the file?有人在不扫描文件的情况下有什么建议吗?

or is there a PHP function that will return the list aliases as an array?或者是否有一个 PHP 函数可以将列表别名作为数组返回?

Any help will be very appreciated.任何帮助将不胜感激。

Assuming I have the following class and the file is located and named as following file name and location src/Foo.php假设我有以下类,并且文件位于并命名为以下文件名和位置 src/Foo.php

namespace Foo;
use Test\One;
use Test\Two;
use Test\Three;

class Sample
{}

now I can scan this file现在我可以扫描这个文件

with this function, I can scan that class and get the result expected.使用此功能,我可以扫描该类并获得预期的结果。

<?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]
    }
}

I think there should be a better way to get the same results and this is why I posted my current solution.我认为应该有更好的方法来获得相同的结果,这就是我发布当前解决方案的原因。 Please let me know your thoughts.请让我知道你的想法。

你可以尝试使用这个类:

https://gist.github.com/Zeronights/7b7d90fcf8d4daf9db0c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM