Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to get name of current class from an uninstantiated object in PHP?

Tags:

php

I know you can use get_class($this) normally but I need to get the name of the class in a static function where the object hasn't been instantiated.

See the following code:

class ExampleClass
{
    static function getClassName()
    {
        echo get_class($this); // doesn't work unless the object is instantiated.
    }
}

$test1 = new ExampleClass();
$test1->getClassName(); // works

ExampleClass::getClassName(); // doesn't work
like image 342
Andrew G. Johnson Avatar asked Jan 24 '09 22:01

Andrew G. Johnson


2 Answers

I think you're looking for the get_called_class() function, if you wish to get the class name from a static method.

See get_called_class documentation for more information.

like image 76
Eddie Parker Avatar answered Nov 14 '22 21:11

Eddie Parker


I figured out you can use __CLASS__ to get the class name. Example:

class ExampleClass
{
    static function getClassName()
    {
        echo __CLASS__;
    }
}
like image 28
Andrew G. Johnson Avatar answered Nov 14 '22 21:11

Andrew G. Johnson