簡體   English   中英

如何從PHP的父類中列出類的子方法而沒有靜態信息?

[英]How do you list child methods of a class from a parent class in PHP without statics?

假設這樣的類結構:

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可以檢查子類,而不必更改子類或引入靜態方法或變量或使用后期靜態綁定。

但是,它確實帶來了開銷,但是解決了上述技術問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM