0

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.

jerryurenaa
  • 3,863
  • 1
  • 27
  • 17
  • Does this answer your question? [Get use statement from class](https://stackoverflow.com/questions/30308137/get-use-statement-from-class) (Spoilers: there doesn't seem to be a way without actually parsing the file, and I'd be surprised if there was.) – Jeto Sep 24 '20 at 19:41
  • It is indeed very easy by scanning the file but I thought there was a PHP defined function for this. I Will post my current solution to approach this. – jerryurenaa Sep 24 '20 at 20:47

2 Answers2

0

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.

jerryurenaa
  • 3,863
  • 1
  • 27
  • 17
0

You can try to use this class:

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

Mark
  • 11
  • 2