I'm trying to use the php function method_exists, but I need to check if the method exists in the parent class of an object.
so:
class Parent
{
public function myFunction()
{
/* ... */
}
}
class Child extends Parent
{
/* ... */
}
$myChild = new Child();
if (method_exists($myChild, 'myFunction'))
{
/* ... */
}
if (method_exists(Parent, 'myFunction'))
{
/* ... */
}
if (is_callable(array('Parent', 'myFunction'))
{
/* ... */
}
But none of the above are working. I'm not sure what to try next.
Thanks for any help!
You should use PHP's Reflection API:
And if you want to know in which (parent) class the method lives:
RobertPitt is correct in that the
Child
class is not a child class unless it extends theParent
class. But from your original code snippet, the following should be true:Note the 'Parent' is in quotes, you had it unquoted. Passing the class name as a string.
Class child must extend the parent in that case
UpdateThis would have the same effect as method_exists I believe.Just updated from Wrikken's post
If you want to know specifically if it exists in the parent, and not only in your own class:
Wouldn't method_exists and get_parent_class combined also work if done within the child class?
For instance
The excample: if (method_exists('Parent', 'myFunction') does not work in PHP 5.3.5 if you like to check for a parent constructor.
But this worked for me:
It calls the Parent Constructor only if the it exists in the parent class