如何从PHP的父类中列出类的子方法而没有静态信息?

时间:2018-10-25 20:56:57

标签: php class oop methods

假设这样的类结构:

class A {
    function __construct() {
        $methods_get_class = get_class_methods(get_class());
        $methods_get_called_class = get_class_methods(get_called_class());

        // The same methods are often the same
        // So you may not be able to get the list
        // of the methods that are only in the child class
    }
}

Class B extends A {
    function __construct() {
        parent::__construct();
    }
}

您将如何列出仅在子类中而不在父类中的方法?

1 个答案:

答案 0 :(得分:1)

做到这一点的一种方法是通过ReflectionClass

$child_class_name = get_called_class();
$child_methods    = (new ReflectionClass($child_class_name))->getMethods();
$child_only_methods = [];
foreach($child_methods as $object){
    // This step allows the code to identify only the child methods
    if($object->class == $child_class_name){
        $child_only_methods[] = $object->name;
    }
}

使用ReflectionClass可以检查子类,而不必更改子类或引入静态方法或变量或使用后期静态绑定。

但是,它确实带来了开销,但是解决了上面的技术问题。