繁体   English   中英

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

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

例子

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

我认为应该有更好的方法来获得相同的结果,这就是我发布当前解决方案的原因。 请让我知道你的想法。

你可以尝试使用这个类:

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

暂无
暂无

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

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