Getting the subclass name in the parent class

Reading Time: < 1 minute

A mistake that I keep making – I have a class that extends another class, and I need to know the class name of that subclass. However the function where I need the name is in the parent class. In this case the magic constant __CLASS__ won’t work, as it will return the name of the class where it is found. get_class() won’t work, too. Not without an important difference:

[code lang=”php”]
abstract class Foo
{
public function getClassName()
{
return __CLASS__;
// or return get_class();
}

public function getSubClassName()
{
return get_class($this); // the reference $this is important here
}
}

class Bar extends Foo {};

$bar = new Bar();

echo ‘1. ‘ . $bar->getClassName();
echo ‘<br>’;
echo ‘2. ‘ . $bar->getSubClassName();
[/code]

This will result in

1. Foo
2. Bar

The first function call returns the (in my case) incorrect name of the parent class, while the 2nd function works as I need it.

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept the Privacy Policy

This site uses Akismet to reduce spam. Learn how your comment data is processed.