PHP Reflection:如何知道ReflectionMethod是否被继承? [英] PHP Reflection: How to know if a ReflectionMethod is inherited?

查看:95
本文介绍了PHP Reflection:如何知道ReflectionMethod是否被继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the ReflectionMethod documentation, I can't find anything to know wether a method was inherited from its parent class or defined in the reflected class.

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

I use ReflectionClass::getMethods(). I want to know for each method if it has been defined in the class being reflected, or if it has been defined in a parent class. In the end, I want to keep only the methods defined in the current class.

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

class Bar extends Foo {
    function a() {}
    function c() {}
}

我想保留ac.

推荐答案

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

You should be able to call ReflectionMethod::getDeclaringClass() to get the class declaring the method. Then a call to ReflectionClass::getParentClass() to get the parent class. Lastly a call to ReflectionClass::hasMethod() will tell you if the method was declared in the parent class.

示例:

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

这篇关于PHP Reflection:如何知道ReflectionMethod是否被继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆