jeudi 6 avril 2017

How to get property class namespace in php 5.6 via reflection

I want to get the namespace of a class property through ReflectionClass.

namespace Foo\Bar;
use Foo\Quux\B;

class A{

   /**
   * @var B $b
   */
   protected $b = null;

   ...

}

In another class I'm creating a ReflectionClass object and trying to get the namespace of property b so I could create ReflectionClass for it's class.

$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");

Is there a possibility to find out which namespaces the class A uses? Then I could pair the namespaces which class A is using with the discovered property type.

I know I can solve this problem with a type hinting like this: @var Foo\Quux\B $b, but I have many classes like the class A with many properties and methods using types like b and I don't want to refactor the whole code.

Is it possible to find the namespaces from the use statement or I have to use explicit type hinting?

Thanks!





Aucun commentaire:

Enregistrer un commentaire