PHP反思:如何知道ReflectionMethod是否被继承?

Mat*_*oli 4 php reflection php-5.3

ReflectionMethod文档中,我找不到任何知道方法是从其父类继承还是在反射类中定义的方法.

编辑:我使用ReflectionClass :: getMethods().我想知道每个方法是否已在被反映的类中定义,或者是否已在父类中定义.最后,我想只保留当前类中定义的方法.

class Foo {
    function a() {}
    function b() {}
}

class Bar extends Foo {
    function a() {}
    function c() {}
}
Run Code Online (Sandbox Code Playgroud)

我想保持ac.

Mit*_*aro 5

您应该能够调用ReflectionMethod :: getDeclaringClass()来获取声明该方法的类.然后调用ReflectionClass :: getParentClass()来获取父类.最后,对ReflectionClass :: hasMethod()的调用将告诉您该方法是否在父类中声明.

例:

<?php
class Foo {
    function abc() {}
}

class Bar extends Foo {
    function abc() {}
    function def() {}
}


$bar = new Bar();

$meth = new ReflectionMethod($bar, "abc");
$cls = $meth->getDeclaringClass();
$prnt = $cls->getParentClass();

if ($cls->hasMethod($meth->name)) {
    echo "Method {$meth->name} in Bar\n";
}
if ($prnt->hasMethod($meth->name)) {
    echo "Method {$meth->name} in Foo\n";
}

$meth = new ReflectionMethod($bar, "def");
$cls = $meth->getDeclaringClass();
$prnt = $cls->getParentClass();

if ($cls->hasMethod($meth->name)) {
    echo "Method {$meth->name} in Bar\n";
}
if ($prnt->hasMethod($meth->name)) {
    echo "Method {$meth->name} in Foo\n";
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*ila 5

您可以获取ReflectionMethod感兴趣的方法的对象,然后使用getPrototype()来获取ReflectionMethod父类中方法的。如果该方法未覆盖父级中的方法,则将引发ReflectionClass异常。

下面的示例代码将创建一个数组,其中方法名称为键,而该类定义了用于反射类的实现。

class Base {
    function basemethod() {}
    function overridein2() {}
    function overridein3() {}
}
class Base2 extends Base {
    function overridein2() {}
    function in2only() {}
    function in2overridein3 () {}
}
class Base3 extends Base2 {
    function overridein3() {}
    function in2overridein3 () {}
    function in3only() {}
}

$rc = new ReflectionClass('Base3');
$methods = array();
foreach ($rc->getMethods() as $m) {
    try {
        if ($m->getPrototype()) {
            $methods[$m->name] = $m->getPrototype()->class;
        }
    } catch (ReflectionException $e) {
        $methods[$m->name] = $m->class;
    }
}

print_r($methods);
Run Code Online (Sandbox Code Playgroud)

这将打印:

Array
(
    [overridein3] => Base
    [in2overridein3] => Base2
    [in3only] => Base3
    [overridein2] => Base
    [in2only] => Base2
    [basemethod] => Base
)
Run Code Online (Sandbox Code Playgroud)