簡體   English   中英

php-擴展給定類的所有類的列表

[英]php - list of all classes that extends a given class

我正在建立一點cms,我想知道哪種是最好的方法。

假設我有類myClassAmyClassBmyClassC ,它們擴展了給定的類myClass

我需要一個函數來列出擴展MyClass所有類MyClass* 是否有一種簡單安全的方法可以僅使用PHP來執行此操作,還是應該將列表保留在其他位置(可能是數據庫中的表)?

我希望這個問題很清楚...

我會用scandir(C:// .... / [包含文件的目錄]); 獲取包含所選目錄中所有文件和文件夾的數組。

然后,我將刪除“。” 和“ ..”,因為它們用於目錄導航。 然后在foreach()循環中,使用if(!is_dir($ single_item))來獲取不是目錄的所有文件。 之后,您將獲得文件和目錄的列表。 然后,我將刪除目錄導航“。” 和數組中的“ ..”。

然后像以前一樣,我將使用file_get_contents()讀取文件的內容,然后使用explode()將單詞拆分成[space]。 然后,我將使用preg_match()使用正則表達式'〜MyClass [A-Za-z0-9]〜'(或其他適用的表達式),並將所有匹配項存儲在數組中。 我最終將通過使用array_filter()過濾它們以獲取可以使用的唯一列表,但是您喜歡

//directory to scan
$dir = "C:\ ...\[directory you want]";

//scan root directory for files
$root = scandir($dir);

//delete directory listings from array (directory navigation)
$disallowed_values = array(".", "..");
foreach($disallowed_values as $disallowed)
{
    if(($key = array_search($disallowed, $root)) !== false)
    {
        unset($root[$key]);
    }
}

//if array is not empty (no files / folders found)
if(! empty($root))
{
    //empty array for items you want found.
    $class_array = array();

    //for each directory
    foreach($root as $item)
    {
        if(! is_dir("$dir" . DIRECTORY_SEPARATOR . "$item"))
        {
            //get file contents
            $file_content = file_get_contents("$dir" . DIRECTORY_SEPARATOR . "$item");

            //pattern to search for
            $pattern = "~MyClass[A-Za-z0-9]*~";

            //create array with results for single file
            preg_match_all($pattern, $file_content, $result);

            //use $result to populate class_array(); use print_r($result); to check what it is outputting (based on your file's structures)
        }
    }
}

//get unique items from array_filter - remove duplicates
$class_array = array_filter($class_array);

//use array of items however you like

暫無
暫無

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

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