tags:

views:

915

answers:

3

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
+1  A: 

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

class ExampleClass
{
    static function getClassName()
    {
        echo __CLASS__;
    }
}
Andrew G. Johnson
Note that __CLASS__ will return the class where the function is defined. If you extend it, you won't get the subclass.
troelskn
@troelskn: could very well bite the asker in the ass. You should submit this as an answer too so more people see it.
Crescent Fresh
+2  A: 

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.

Eddie Parker
A: 

My question is, how are you managing to call a static function without knowing the class name in the first place?

The only two ways I can think of are:

ExampleClass::getClassName(); //Hard Coded - the class name is hard and visible
$class = "ExampleClass";
$class::getClassName();       //Soft Coded - the class name is the value of $class

Perhaps a better solution could be offered if we knew the context in which you are trying to make the call?

J. Kenzal Hunter Sr.
I'm calling an inherited class and there is a switch() statement in the parent class that requires the class name to decide what to do
Andrew G. Johnson
What is the variable data from which you are trying to switch that would require a static function?
J. Kenzal Hunter Sr.