Reputation: 3971
I have a classname saved in a string in PHP. Is it possible to resolve the class name using a string?
If assuming that I have a class called 'Myclass', I need something like:
'Myclass'::class
Upvotes: 3
Views: 97
Reputation: 5022
I'm not entirely clear what use you'd have for ::class
against a string. The simple fact is that, if this worked, it would just output the same string as you already have. ie in your example, 'MyClass'::class
would output the string MyClass
.
Maybe you're trying to have a string that just contains the classname and you're trying to resolve the namespace? This won't work. But you can get the current namespace using the __NAMESPACE__
reserved word:
namespace foo\bar;
echo __NAMESPACE__; //will output 'foo\bar'
You can use this in conjunction with a classname string to build a fully-qualified classname for the current namespace.
If you want to get a classname from a different namespace, then you will have to know the namespace beforehand; without the namespace, PHP won't be able to locate the class at all.
Upvotes: 1