如何确定方法是继承的、重新定义的还是新的 (PHP)

jav*_*xin 2 php methods inheritance

我想要一个函数来检查一个类是否定义了某个方法,类似于,但是如果提到的方法存在并且它是在 obj 类本身中定义的,而不是继承的,那么method_exists类似的函数将返回 true。method_defined($obj, 'method_name');对于未继承的新方法,它应该返回 true (这可以很好地检查方法是否在父类中定义,例如method_exists($obj, $method) && !method_exists(get_parent_class($obj), $method)),对于重新定义的继承方法(不知道如何执行)也应该返回 true,但返回false 对于未重新定义的继承方法(也不知道)。

示例代码:

<?php
class base
{
    var $x = 'x';
    function doit()
    {
        return $this->x;
    }
}

class a extends base
{
    function doit()
    {
        return 'a';
    }
}

class b extends base
{
    var $x = 'b';
}

class c extends base
{
}

function method_defined($obj, $method)
{
    return method_exists($obj, $method); // this is the question
}

function info($obj)
{
    echo get_class($obj) . ": " . $obj->doit();
    echo " " . (int)method_exists($obj, 'doit');
    echo " " . (int)is_subclass_of($obj, 'base');
    echo " " . (int)method_defined($obj, 'doit') . "\n";
}

info(new a); // a a 1 1 1
info(new b); // b b 1 1 0
info(new c); // c x 1 1 0
info(new base); // base x 1 0 1
Run Code Online (Sandbox Code Playgroud)

我见过其他类似的问题,但它们都回到了 Reflection 类,如果可能的话,我想避免它,因为它非常重。

提前致谢。

jav*_*xin 5

最后,这就是我用作解决方案的方法。它使用反射,但非常简单有效。

function method_defined($ref, $method)
{
    $class = (is_string($ref)) ? $ref : get_class($ref);
    return (method_exists($class, $method)) && ($class === (new \ReflectionMethod($class, $method))->getDeclaringClass()->name);
}
Run Code Online (Sandbox Code Playgroud)