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.

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: