dongre6073 2017-03-18 17:27
浏览 52
已采纳

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

I would like a function that checks if a class defines a certain method, similar to method_exists, but something like method_defined($obj, 'method_name'); that would return true if the mentioned method exists AND it is defined in the obj class itself, not inherited. It should return true for new methods not inherited (this would be fine checking if method is defined or not in parent class, something like method_exists($obj, $method) && !method_exists(get_parent_class($obj), $method)) and also true for inherited methods that are redefined (don't know how to do it), but return false for inherited methods that are not redefined (don't know either).

Sample code:

<?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') . "
";
}

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

I have seen other similar questions, but they all revert to the Reflection class for this, and I would like to avoid it if at all possible, because it is very heavy.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • douqian8238 2017-05-17 16:42
    关注

    Finally, this is what I used as a solution. It uses Reflection, but it is quite simple and effective.

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?