5

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
  • You might want to edit your question to read that you understand that $this has no meaning in the static case - I think some people might simply think you don't understand what '$this' means. See my answer about get_called_class, as well. Commented Jan 24, 2009 at 22:33

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

class ExampleClass { static function getClassName() { echo __CLASS__; } } 

2 Comments

Note that CLASS will return the class where the function is defined. If you extend it, you won't get the subclass.
@troelskn: could very well bite the asker in the ass. You should submit this as an answer too so more people see it.
0

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?

2 Comments

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
What is the variable data from which you are trying to switch that would require a static function?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.