PHP 从子类中获取覆盖的方法

标签 php reflection

给定以下情况:

<?php

class ParentClass {

    public $attrA;
    public $attrB;
    public $attrC;

    public function methodA() {}
    public function methodB() {}
    public function methodC() {}

}

class ChildClass extends ParentClass {

    public $attrB;

    public function methodA() {}
}

如何获取在 ChildClass 中被覆盖的方法列表(最好是类变量)?

谢谢, 乔

编辑:修复了错误的扩展。任何方法,而不仅仅是公共(public)方法。

最佳答案

反射是正确的,但你必须这样做:

$child  = new ReflectionClass('ChildClass');

// find all public and protected methods in ParentClass
$parentMethods = $child->getParentClass()->getMethods(
    ReflectionMethod::IS_PUBLIC ^ ReflectionMethod::IS_PROTECTED
);

// find all parent methods that were redeclared in ChildClass
foreach($parentMethods as $parentMethod) {
    $declaringClass = $child->getMethod($parentMethod->getName())
                            ->getDeclaringClass()
                            ->getName();

    if($declaringClass === $child->getName()) {
        echo $parentMethod->getName(); // print the method name
    }
}

Properties 也一样,只是您会使用 getProperties() 代替。

关于PHP 从子类中获取覆盖的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2669046/

相关文章:

javascript - 如何从 html Canvas CanvasGradient 和 CanvasPattern 对象中提取属性

php - 使用删除查询时 PHP 代码中的结果始终为 TRUE

php - Laravel:在模型类中实现方法的最佳方式是什么

php - 同一时间在一行上的多个 Update 语句

ldap - PHP如何指定ldap.conf位置?

c# - 我想通过反射得到一个方法

java - 使用反射查找方法是否重载

php - 我如何在 PHP 中加入来自两个不同文件夹的两个文本文件?

reflection - 如何使用反射制作 map 指针?

Java反射: internals of java. lang.reflect.Field.getDouble(object)