Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method_exists in parent class php

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!

like image 912
Serg Avatar asked Jul 22 '10 10:07

Serg


People also ask

What annotation is used to check if a method exists in a parent class?

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.

How do you call a method from child class to parent class in PHP?

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.

What is parent keyword in PHP?

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.


2 Answers

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

like image 78
RobertPitt Avatar answered Sep 22 '22 16:09

RobertPitt


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'
like image 27
Dennis Haarbrink Avatar answered Sep 20 '22 16:09

Dennis Haarbrink