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!
We use the @Override annotation to mark a method that exists in a parent class, but that we want to override in a child class.
Case1. We can't run directly the parent class constructor in child class if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
parent allows access to the inherited class, whereas self is a reference to the class the method running (static or otherwise) belongs to. A popular use of the self keyword is when using the Singleton pattern in PHP, self doesn't honour child classes, whereas static does New self vs. new static.
Class child must extend the parent in that case
class Parent
{
public function hello()
{
}
}
class Child extends Parent
{
}
$child = new Child();
if(method_exists($child,"hello"))
{
$child->hello();
}
Update This would have the same effect as method_exists I believe.
function parent_method_exists($object,$method)
{
foreach(class_parents($object) as $parent)
{
if(method_exists($parent,$method))
{
return true;
}
}
return false;
}
if(method_exists($child,"hello") || parent_method_exists($object,"hello"))
{
$child->hello();
}
Just updated from Wrikken's post
You should use PHP's Reflection API:
class Parend
{
public function myFunction()
{
}
}
class Child extends Parend{}
$c = new Child();
$rc = new ReflectionClass($c);
var_dump($rc->hasMethod('myFunction')); // true
And if you want to know in which (parent) class the method lives:
class Child2 extends Child{}
$c = new Child2();
$rc = new ReflectionClass($c);
while($rc->getParentClass())
{
$parent = $rc->getParentClass()->name;
$rc = new ReflectionClass($parent);
}
var_dump($parent); // 'Parend'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With