在没有静态的PHP中,如何从父类中列出类的子方法?
假设类结构如下:在没有静态的PHP中,如何从父类中列出类的子方法?,php,class,oop,methods,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
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 使用ReflectionClass允许检查子类,而无需更改子类、引入静态方法或变量或使用后期静态绑定 但是,它确实会带来开销,但它解决了上述技术问题。添加ReflectionMethod::IS_PRIVATE或类似内容将允许您将列表筛选为匹配的方法:
$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;
}
}