从课堂上获取使用声明 [英] Get use statement from class
问题描述
不确定最好的标题,但我会尽我所能解释.假设我有以下文件:
Not quite sure of the best title but I will explain what I am asking as best I can. Assume 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 were to use reflection, I could get the fully qualified class names from the type hints in the construct.
但是,我会收到FooNamespace\FooClass
和BarNamespace\BarClass
.不是,FooNamespace\FooClass
和BarNamespace\Bar
.我也不会引用BazNamespace\BazClass
.
However, I would recieve FooNamespace\FooClass
and BarNamespace\BarClass
. Not, FooNamespace\FooClass
and BarNamespace\Bar
. I would also get no reference to BazNamespace\BazClass
.
基本上,我的问题是:如何在仅知道FooClass
,Bar
和BazSpecial
的情况下从MyCustomClass.php
获取完全限定的名称?
Basically, my question is: How can I get the fully qualified names from MyCustomClass.php
while only knowing FooClass
, Bar
, and, BazSpecial
?
我不想使用文件解析器,因为这会影响性能.我希望能够做类似的事情:
I do not want to use a file parser as this will eat performance. 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
我该怎么做?
推荐答案
由于没有人回答,我认为没有简单的方法可以实现这一目标.因此,我创建了自己的名为ExtendedReflectionClass
的类,该类可以满足我的需求.
Seeing as no one has answered, I assume there is not an easy way to achieve this. I have therefore created my own class called ExtendedReflectionClass
which achieves what I need.
我用类文件和自述文件创建了要点,该文件位于底部,因此可以滚动!!
I have created a gist with the class file and a readme, which is at the bottom so get scrolling!.
用法示例:
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
这篇关于从课堂上获取使用声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!