【问题标题】:Is it possible to get the list of the class alias in php as array?是否可以将 php 中的类别名列表作为数组获取?
【发布时间】:2021-01-11 03:31:00
【问题描述】:

例子

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

class Sample
{}

如何将别名 (USE) 作为数组获取?

我希望得到的示例

$test = [测试\一,测试\二,测试\树];

有没有人不扫描文件有什么建议?

或者是否有 PHP 函数将列表别名作为数组返回?

任何帮助将不胜感激。

【问题讨论】:

  • 这能回答你的问题吗? Get use statement from class(剧透:似乎没有办法不实际解析文件,如果有的话我会感到惊讶。)
  • 通过扫描文件确实很容易,但我认为有一个PHP定义的函数。我将发布我当前的解决方案来解决这个问题。

标签: php laravel codeigniter namespaces alias


【解决方案1】:

你可以尝试使用这个类:

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

【讨论】:

    【解决方案2】:

    假设我有以下类并且文件被定位并命名为以下文件名和位置 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]
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 1970-01-01
      • 2011-08-05
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多