简体   繁体   中英

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?

example of what I am looking to get

$test = [Test\\One, Test\\Two, Test\\Tree];

Does anybody have any suggestions without scanning the file?

or is there a PHP function that will return the list aliases as an array?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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