php - method_exists 在父类 php

标签 php parent-child

我正在尝试使用 php 函数 method_exists,但我需要检查该方法是否存在于对象的父类中。

所以:

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'))
{
    /* ... */
}

但以上都不起作用。我不确定接下来要尝试什么。

感谢您的帮助!

最佳答案

在这种情况下,子类必须扩展父类

class Parent
{
   public function hello()
   {

   }
}

class Child extends Parent
{

}

$child = new Child();

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

Update 我认为这与 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();
}

刚刚从 Wrikken 的帖子中更新

关于php - method_exists 在父类 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3307938/

相关文章:

java - 在没有类加载父类的情况下调用子类方法?

css - 我应该在哪里添加 <link rel ='stylesheet' 行?

PHP Carbon不计算时差

php - JQuery 帮助处理复选框及其值

php - 如何将 PHP 变量值添加到 Between Query

javascript - ReactJS:This.props.toggleModal 不是一个函数

php - 如何一次调用 'off' 所有事件

php - Laravel 4 防止经过身份验证的用户查看其他用户个人资料

postgresql - Postgres 表继承 : move from parent to child and vice versa

.net - 如何将动态的 Observable 集合组合成一个新的 Observable?