[英]How do you list child methods of a class from a parent class in PHP without statics?
Assuming a class structure like this: 假设这样的类结构:
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();
}
}
How would you list the methods that are only in the child class and not in the parent class? 您将如何列出仅在子类中而不在父类中的方法?
One way that this can be done is via ReflectionClass
. 可以做到这一点的一种方法是通过
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;
}
}
Using ReflectionClass allows for inspection of the child class without having to alter the child class or introduce static methods or variables or use late static binding. 使用ReflectionClass可以检查子类,而不必更改子类或引入静态方法或变量或使用后期静态绑定。
However, it does introduce overhead, but it solves the technical problem above. 但是,它确实带来了开销,但是解决了上述技术问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.