Home / Get the class name and parent class name in PHP

Get the class name and parent class name in PHP

Sometimes you need to be able to get the class name or parent class name of an object in PHP to do something conditionally etc. This post looks at how to do this.

The relevent functions are get_class() and get_parent_class() and both can be passed an instance of the object. The get_parent_class() function can also be passed a class name. Both will then return the name of the class as a string.

For example, we have the following two classes:

class foo {
}

class bar extends foo {
}

Then we create an instance of bar:

$bar = new bar;

We can get the class name and parent class name like so:

echo get_class($bar); // will echo 'bar'
echo get_parent_class($bar); // will echo 'foo'
echo get_parent_class('bar'); // will also echo 'foo'

Note that passing the class name as a string to get_class() will not return the class name. You already know the class name if you’re passing it as a string so there wouldn’t be much point calling it anyway.

If you are calling the functions from within the class itself, you can pass it $this. For example, we’ll redefine the above classes as follows:

class foo {

	function my_name_is() {
		return get_class($this);
	}

}

class bar extends foo {

	function my_parent_is() {
		return get_parent_class($this);
	}

}

And then execute the following code:

$foo = new foo;
echo "my name is: ", $foo->my_name_is(), "<br />n";
$bar = new bar;
echo "my name is: ", $bar->my_name_is(), "<br />n";
echo "my parent is: ", $bar->my_parent_is(), "<br />n";

This outputs the following:

my name is: foo
my name is: bar
my parent is: foo

So that’s how you get the class name and parent class name in PHP.