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:
Then we create an instance of bar:
We can get the class name and parent class name like so:
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:
And then execute the following code:
This outputs the following:
So that's how you get the class name and parent class name in PHP.
0 comments:
Post a Comment