In PHP, how can a class reference its own name?
For example, what would the method look like to do this?
Dog::sayOwnClassName();
//echos "Dog";
Update
I see that everyone is saying get_class($this)
. But that's not correct. That would work if I were creating an instance of Dog. I'm asking about calling a method of the Dog class itself. If Dog
extends Mammal
, then a call to get_class($this)
inside the Dog
class will return 'Mammal.'.
In other words:
- I'm not asking "what's the class of the Dog class," to which the answer is, "the Dog class is a member of the Mammal class."
- I'm also not asking "given an instance of Dog the dog class (called Rover), what is its class?", to which the answer is "Dog."
- What I'm asking is, "can the Dog class itself tell me 'my name is Dog?'"
For example:
class Mammal {
public function find_by_id($id){
$query = "SELECT * FROM " . $myclass . " WHERE `id` = " . $id;
//(etc)
return $matching_object;
}
}
class Dog extends Mammal {
//find_by_id method should know to do a SELECT from Dog table
}
Update 2
Yacoby's suggestion of get_called_class()
was correct. Here's how it works in the example I gave.
class Mammal {
public function find_by_id($id){
$myclass = get_called_class();
$query = "SELECT * FROM " . $myclass . " WHERE `id` = " . $id;
//(etc)
return $matching_object;
}
}
class Dog extends Mammal {
//find_by_id knows to do a SELECT from Dog table
//and will return the correct dog object
}