如何在没有静态的情况下从 PHP 中的父类列出类的子方法?



假设类结构如下:

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();
}
}

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

完成此操作的一种方法是通过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 可以检查子类,而无需更改子类或引入静态方法或变量或使用后期静态绑定。

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

最新更新