我想通过ReflectionClass获取类属性的名称空间。如何通过反射在PHP 5.6中获取属性类名称空间
namespace Foo\Bar;
use Foo\Quux\B;
class A{
/**
* @var B $b
*/
protected $b = null;
...
}
在另一类我创建一个ReflectionClass
对象,并试图获得的财产b
的命名空间,这样我可以创建ReflectionClass
为它的类。
$namespace = "Foo\\Bar";
$classname = "A";
$rc = new \ReflectionClass("$namespace\\$classname");
$type = getVarType($rc->getProperty("b")->getDocComment()); // returns B
$ns = $rc->getProperty("b")-> ... // I want to find out the namespace of class B
$rc1 = new \ReflectionClass("$ns\\$type");
是否有可能找出A类使用哪些名称空间? 然后,我可以将class A
正在使用的名称空间与发现的属性类型配对。
我知道我可以用类型提示是这样解决这个问题:@var Foo\Quux\B $b
,但我有很多类,如class A
使用类型,如b
许多属性和方法,我不想重构整个代码。
是否有可能从use
声明中找到名称空间,或者我必须使用显式类型提示?
谢谢!
谢谢你的回答,但这不是我想要的结果。 我想返回的类是'Foo \ A',所以我可以递归地研究它,即。创建'new \ ReflectionClass(“Foo \\ A”);' –
所以在返回的类上执行'str_replace',你可以完成你正在描述的内容 – Machavity
事情是,我真的不知道哪个类或名字空间来首先期望。代码示例中的类“B”可能也有一个属性“$ c”,该类可以是例如“Foobar \ C”或“Bar \ C”。我真的不知道php是否能够发现真正的类,而不是查看将写入完整名称空间的DocComment。 –