This question already has an answer here:
- How do I get class name in PHP? 10 answers
I have an abstract class and an extending class:
abstract class MyAbstract {
public function getName(){echo static::class;}
}
class MyExtends extends MyAbstract {}
I would like to dynamically get the name of any extending class when getName()
is called:
$c = new MyExtends();
echo $c->getName(); // expect: "MyExtends"
This works well on PHP 5.6+ (demo), but the project I'm working on is limited to PHP 5.3 and I have no leverage to change that. On that version, a parse error is thrown:
Parse error: syntax error, unexpected T_CLASS, expecting T_STRING or T_VARIABLE or '$'
So I modified the function to:
public function getName(){echo __CLASS__;}
Of course, this just echoes the parent name -- MyAbstract
, so it doesn't work. Only thing I've thought of is to override getName()
with a new implementation in each extending class, but that doesn't scale well: the whole point of inheritance is to concentrate common codebase in a parent (and of course the real function is not a one-liner).
Any idea how I can dynamically get the extending class name from the context of the abstract parent class in PHP 5.3?
</div>