PHP: How to get a fully qualified class name from an alias?

落花浮王杯 提交于 2019-12-01 03:25:00

In PHP 5.5 onwards you can do this using ::class:

echo MyClass::class;

Unfortunately this is not possible at all on earlier versions, where you have to either hardcode the class name or create an instance first and use get_class on it.

On early PHP version (that is, PHP < 5.5) you can get the class name via Reflection API, like this:

namespace App\Core;

use Symfony\Component\Form\Extension\Core\Type;

class MyClass {}

$refclass = new \ReflectionClass(new Type\DateType);
print $refclass->getName();
$refclass = new \ReflectionClass(new MyClass());
print $refclass->getName();

Of course, if this is not expensive for your case.

Note
Since PHP 5.4:

$classname = (new \ReflectionClass(new Type\DateType))->getName();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!