Method_exists in php parent class

I am trying to use the php function function_exists, but I need to check if the method exists in the parent class of the 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 actions work. I'm not sure what to do next.

Thanks for any help!

+5
source share
6 answers

In this case, the child of the class must extend the parent

class Parent
{
   public function hello()
   {

   }
}

class Child extends Parent
{

}

$child = new Child();

if(method_exists($child,"hello"))
{
    $child->hello();
}

Refresh This will have the same effect as method_exists.

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 post

+7
source

You should use the PHP Reflection API:

class Parend
{
  public function myFunction()
  {

  }
}

class Child extends Parend{}

$c = new Child();


$rc = new ReflectionClass($c);
var_dump($rc->hasMethod('myFunction')); // true

, () , :

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'
+9

, , :

foreach(class_parents($this) as $parent){
    if(method_exists($parent,$method){
        //do something, for instance:
        parent::$method();
        break;
    }
}
+4

RobertPitt , Child , Parent. :

if (method_exists('Parent', 'myFunction')
{
  // True
}

, "" , . .

+1

method_exists get_parent_class , ?

class Parent
{

}

class Child extends Parent
{
   public function getConfig()
   {
     $hello = (method_exists(get_parent_class($this), 'getConfig')) ? parent::getConfig() : array();
   }
}
+1

:   if (method_exists ( "", "myFunction" ) PHP 5.3.5, .

:

class Child extends Parent {
  function __construct($argument) {
    if(method_exists(get_parent_class(),"__construct")) parent::__construct($argument)
  }
}

,

0

All Articles