Getting the name of a child class in the parent class (static context)
You don't need to wait for PHP 5.3 if you're able to conceive of a way to do this outside of a static context. In php 5.2.9, in a non-static method of the parent class, you can do:
get_class($this);
and it will return the name of the child class as a string.
i.e.
class Parent() { function __construct() { echo 'Parent class: ' . get_class() . "\n" . 'Child class: ' . get_class($this); }}class Child() { function __construct() { parent::construct(); }}$x = new Child();
this will output:
Parent class: ParentChild class: Child
sweet huh?
in short. this is not possible. in php4 you could implement a terrible hack (examine the debug_backtrace()
) but that method does not work in PHP5. references:
edit: an example of late static binding in PHP 5.3 (mentioned in comments). note there are potential problems in it's current implementation (src).
class Base { public static function whoAmI() { return get_called_class(); }}class User extends Base {}print Base::whoAmI(); // prints "Base"print User::whoAmI(); // prints "User"
I know this question is really old, but for those looking for a more practical solution than defining a property in every class containing the class name:
You can use the static
keyword for this.
As explained in this contributor note in the php documentation
the
static
keyword can be used inside a super class to access the sub class from which a method is called.
Example:
class Base{ public static function init() // Initializes a new instance of the static class { return new static(); } public static function getClass() // Get static class { return static::class; } public function getStaticClass() // Non-static function to get static class { return static::class; }}class Child extends Base{}$child = Child::init(); // Initializes a new instance of the Child class // Output:var_dump($child); // object(Child)#1 (0) {}echo $child->getStaticClass(); // Childecho Child::getClass(); // Child