bijiDango
bijiDango

Reputation: 1596

How to obtain class name in a static method in PHP?

Actually my problem is more complicated than the title says.

I want to have a base class with a static method, and the method should be able to obtain the class name of the current class.

class Base
{
    public static function className()
    {
        return '???';
    }
}

class Foo extends Base
{

}

echo Foo::className();

I expect Foo to be the output.


As some pointed out that in php5.5 it is simple with static::class, I should say I have to use PHP5.3 allowing for the framework we are using. :(

Upvotes: 2

Views: 1016

Answers (3)

Hereblur
Hereblur

Reputation: 2174

For PHP >=5.3 you can use get_called_class().

Example copied from http://php.net/get_called_class

<?php

class foo {
    static public function test() {
        return get_called_class();
    }
}

class bar extends foo {
}

print foo::test();
print bar::test();
?>

The above example will output:

foo
bar

Upvotes: 0

Md. Abutaleb
Md. Abutaleb

Reputation: 1645

Simply Try this following with static::class or get_called_class() both will return the Class name from which class calling this static method

<?php
class Base
{
    public static function className()
    {
        return static::class;
      // or
      //return get_called_class()
    }
}

class Foo extends Base
{

}
class Doo extends Base
{

}
echo Foo::className(); // Output will be Foo
echo Bar::className(); // Output will be Bar

Reference : http://php.net/manual/en/language.oop5.basic.php

http://php.net/get_called_class

Upvotes: 3

Rei
Rei

Reputation: 6363

You can use static::class since PHP 5.5, like this:

return static::class;

Upvotes: 3

Related Questions