Last week I looked at how to see if a function exists in PHP and this time will look at how to check if a class method exists in PHP.
Let's say we have the following example PHP class:
Use the method_exists() function to check to see if a method exists like so (the (int) part casts it as an integer so it will display 0 if false and 1 if true):
The first line will echo 1 (true) because the 'bar' method does exists in the 'foo' class. The second line will echo 0 (false) because the 'baz' method does not exist.
You can also pass an object itself to the method_exists() function:
Again, the first line will echo 1 and the second line 0.
Note that if a method is declared as private or protected, the function will still return true if it exists, even though you will not be able to call it (although of course you can call a protected method if it's a child class).
For example, a modified version of the above class:
And checking if the x, y, z methods exist:
Each of these will echo 1 because they do exist, although you may not be able to call them all. So use with caution!
In one of next week's PHP posts I'll look at the is_callable() function. Make sure to sign up to my RSS feed (see details below) so you don't miss out.
0 comments:
Post a Comment