Peter Fox
Peter Fox

Reputation: 1849

Get fully qualified class name from unqualified class name

How can I make this work?

<?php
namespace Target {
  
  class FooBar {
  
  }
}

namespace Test {
  
  use Target\FooBar;

  $class = 'FooBar';

  var_dump(new \ReflectionClass(new $class));

}

At the moment it fails because Reflection class only finds classes with the full namespace. How can I change this so that it will pickup the class from the use statements? If there a function I'm missing. Trying things like $class::class also just makes an error.

My full purpose is to be able to work with annotations for arrays like so:

<?php
namespace Target {
  use Foo\Bar;
  
  class FooBar {
    /**
     * @var Bar[]|null
     */
    public ?array $foo;
  }
}

Maybe what I'm doing is impossible and I should just have the fully qualified class name in the annotations.

I'm working with PHP7.4

Upvotes: 0

Views: 1023

Answers (1)

Mikhail Prosalov
Mikhail Prosalov

Reputation: 4345

I'm afraid it's not possible. According to PHP documentation a fully qualified class name should be used in a dynamic class name.

One must use the fully qualified name (class name with namespace prefix). Note that because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name, the leading backslash is not necessary.

<?php

namespace Target {
    class FooBar
    {
    }
}

namespace Test {
    $class = 'Target\FooBar';

    var_dump(new \ReflectionClass(new $class));
}

As an alternative, there is an option to parse use statements and grab fully qualified class name from there, this way is a bit hacky though. github.com/Kdyby/ParseUseStatements

Upvotes: 1

Related Questions