3
votes

I've found that by using ::class, I can get the fully qualified class name of a namespaced class:

namespace NameSpace {
    class Foo { }
    echo Foo::class;
}
// echoes 'NameSpace\Foo'

But I can't figure out a way to do this with a variable class name. Trying to treat the class keyword like a static property doesn't seem to work:

namespace NameSpace {
    class Foo { }
    $className = 'Foo';
    echo $className::class;
}
// Parse error: syntax error, unexpected 'class'

Does anyone know if its possible to get the fully qualified class name dynamically like I'm trying to?


I want to be able to do this with classes from outside the current namespace:

namespace ReallyLongHardToWriteNameSpace {
    class Foo { }
}
namespace NameSpace {
    use ReallyLongHardToWriteNameSpace\Foo;
    class Bar { }

    echo Foo::class; // echoes 'ReallyLongHardToWriteNameSpace\Foo'
    echo Bar::class; // echoes 'NameSpace\Bar'

    foreach (['Foo', 'Bar'] as $className) {
        echo $className::class; // Parse error: syntax error, unexpected 'class'
    }
}
3

3 Answers

0
votes

You can use get_class with an instance of that class:

<?php
namespace NS {
    class Foo { }
    $className = "\\NS\\Foo";
    echo get_class(new $className);
}
// prints NS\Foo

Do note that to create an instance of the class I had to use the FQN in the string, so it might not be useful at all.

0
votes

Ok, I came up with another solution. Even tho this is somewhat different.

namespace NameSpace;
class Foo {
    public static function getFullName() {
        return __CLASS__;
    }
}

print Foo::getFullName(); // Prints NameSpace\Foo

Just create a abstract class which has getFullName() as method and inherit from it on all classes you want to be able to return full name.


Simplest approch (I almost forgot) is the use of get_class()

$className = get_class($yourClassObject); // returns NameSpace\Foo

You can also try using eval() for this.

$className = 'NameSpace\Foo::class';
eval('$fullName = ' . $className);
print $fullName; // returns NameSpace\Foo

Even tho, this might not be exactly what you want, but you should look at the Reflection library. Its very handy to use for such things.

// Lets say you have an object of your class
$object = new ReflectionObject($yourObject);
$name = $object->getName(); // will return NameSpace\Foo

// You can also give the class name to it
$class = new ReflectionClass('Foo');
$name = $class->getName(); // also returns NameSpace\Foo

Look here for more information There are also classes for methods, properties, etc.

0
votes

You can use __NAMESPACE__ to get the current namespace, then just prepend that to the string that contains the class name.

namespace NS {
    class Foo {
    }
    $className = 'Foo';
    echo __NAMESPACE__ . '\\' . $className;
}