Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In PHP, if I want to get the fully qualified class name of a class that's included with a use statement, how do I do that? For instance,

<?php
namespace MyNamespace;

use Namespace\To\Class as MyClass;

function getNamespaceOfMyClass() {
    // Return ??
}

echo getNamespaceOfMyClass();

I know one way is to do get_class(new MyClass()), but what if I can't/don't want to make an instance of MyClass? Thanks!

like image 868
osdiab Avatar asked Nov 08 '13 23:11

osdiab


2 Answers

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.

like image 109
Jon Avatar answered Oct 04 '22 18:10

Jon


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();
like image 45
felipsmartins Avatar answered Oct 04 '22 18:10

felipsmartins