Get usage instructions from the class

Not quite sure of the best title, but I will explain what I ask, as much as possible. Suppose I have the following file:

MyCustomClass.php

<?php namespace MyNamespace; use FooNamespace\FooClass; use BarNamespace\BarClass as Bar; use BazNamespace\BazClass as BazSpecial; class MyCustomClass { protected $someDependencies = []; public function __construct(FooClass $foo, Bar $bar) { $someDependencies[] = $foo; $someDependencies[] = $bar; } } 

Now, if I used reflection, I could get fully qualified class names from the types of hints in the construct.

However, I would get FooNamespace\FooClass and BarNamespace\BarClass . No, FooNamespace\FooClass and BarNamespace\Bar . I would also not refer to BazNamespace\BazClass .

Basically, my question is: how to get full names from MyCustomClass.php , only knowing FooClass , Bar and BazSpecial ?

I do not want to use a file parser, as this will work. I want to be able to do something like:

 $class = new ReflectionClass('MyCustomClass'); ... $class->getUsedClass('FooClass'); // FooNamespace\FooClass $class->getUsedClass('Bar'); // BarNamespace\BarClass $class->getUsedClass('BazSpecial'); // BazNamespace\BazClass 

How can I do it?

+8
reflection php namespaces
source share
1 answer

Seeing no one answer, I suppose there is no easy way to achieve this. So I created my own class called ExtendedReflectionClass , which achieves what I need.

I created a gist with the class file and readme, which is located below to get the scroll !.

ExtendedReflectionClass

Usage example :

 require 'ExtendedReflectionClass.php'; require 'MyCustomClass.php'; $class = new ExtendedReflectionClass('MyNamespace\Test\MyCustomClass'); $class->getUseStatements(); // [ // [ // 'class' => 'FooNamespace\FooClass', // 'as' => 'FooClass' // ], // [ // 'class' => 'BarNamespace\BarClass', // 'as' => 'Bar' // ], // [ // 'class' => 'BazNamespace\BazClass', // 'as' => 'BazSpecial' // ] // ] $class->hasUseStatement('FooClass'); // true $class->hasUseStatement('BarNamespace\BarClass'); // true $class->hasUseStatement('BazSpecial'); // true $class->hasUseStatement('SomeNamespace\SomeClass'); // false 
+1
source share

All Articles