19

We have a code

class ParentClass {
  public static function getName() {
    return get_class(self);
  }
}

class ChildClass extends ParentClass {
}

echo ParentClass::getName(); # => 'ParentClass'
echo ChildClass::getName(); # => 'ParentClass'

if I use get_class($this) there is the same result. Also for self::$this, static::$this etc

Any way to get child class name without adding methods to child class for this?

2 Answers 2

31

You'll have to use get_called_class, which binds late. Only available since PHP 5.3 though.

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

Comments

2

Since PHP 5.5 we can use static::class instead of get_called_class:

class ParentClass {
  public static function getName() {
    return static::class;
  }
}

class ChildClass extends ParentClass {
}

echo ParentClass::getName(); # => 'ParentClass'
echo ChildClass::getName(); # => 'ChildClass'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.