[英]php - list of all classes that extends a given class
我正在建立一点cms,我想知道哪种是最好的方法。
假设我有类myClassA
, myClassB
, myClassC
,它们扩展了给定的类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.