从类引用中获取类名称空间和名称,而不更改我的类

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.

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.

namespace test;

class a {

    public function getname()
    {
        return __CLASS__;
    }
}

And:

$a = new a();
echo $a->getname(); // 

Outputs

test\a

Static method works same way:

public static function getname()
{
    return __CLASS__;
}

...

a::getname(); // test\a

You can also get only namespace with __NAMESPACE__

Update: you can you ReflectionClass for same thing:

$a = new a();

$r = new \ReflectionClass($a);
echo $r->getName(); // test\a

you can create ClassHelper class to have it for using anywhere you need it easily:

class ClassHelper
{
    public static function getFullQualifiedName($object)
    {
        $rc = new \ReflectionClass($object);
        return $rc->getName();
    }
}

And use it:

echo ClassHelper::getFullQualifiedName($a); // test\a

Finnaly: if you use php 5.6 and above (for future), you can work with class constant

echo a::class; // test\a