Search code examples
phpreferenceclassname

Get class namespace and name from class reference, without changing my classes


In php you often check if the object you get is of the correct type. If not you throw an exception with a message like this:

use My\Class\MyClass

...

if (!$object instanceof MyClass) {
    throw new Exception(
        sprintf(
            "object must be of type '%s'", 
            'My\Class\MyClass'
        )
    );
}

Right now I pass the full namespace and the name of the class in a string to sprintf.

How can I get this from the class reference so that i can do something like this

sprintf("object must be of type '%s'", MyClass::getName())

EDIT:

I would like to achieve this for all classes without adding new methods. So it should be a solution using some existing method or one of the php __ MAGIC__ methods.


Solution

  • As of php 5.5 there's a magic constant that gives you the FQCN of any class. You can use it like this:

    namespace My\Long\Namespace\Foo\Bar;
    
    MyClass::class;
    // will return "My\Long\Namespace\Foo\Bar\MyClass"
    

    It's documented on the new features page.