Get the class name and parent class name in PHP
Posted November 19th, 2008 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.
Related posts:
- Check if a class exists with PHP (Thursday, December 11th 2008)
- Method chaining with PHP (Sunday, December 7th 2008)
- Get a list of all available classes with PHP (Thursday, July 10th 2008)
- Get a list of all available functions with PHP (Thursday, July 3rd 2008)
Recent posts:
- MySQL queries for article summaries part 2 of 2 (Tuesday, January 6th 2009)
- Aims for 2009 (Monday, January 5th 2009)
- Weekly Roundup - January 5th 2008 (Monday, January 5th 2009)
- MySQL queries for article summaries part 1 of 2 (Sunday, January 4th 2009)
- 2008 Summary of Posts (Saturday, January 3rd 2009)
- 2008 / 2009 overview (Friday, January 2nd 2009)
Subscribe to RSS Feed / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email and have my posts sent in a daily email.
Posts are made using the following schedule (although it may vary some weeks): Mondays & Fridays = PHP; Tuesdays & Saturdays = MySQL; Wednesdays & Sundays = Javascript/jQuery; Thursdays = HTML/CSS.
