类存在于外部文件中 [英] Class exists in an external file
问题描述
如何检查外部文件中的课程?
How do I check an external file for a class?
我试图为我的模块设置安装功能,所以我试图让它加载目录列表,然后检查模块文件是否具有称为install的方法.因此,只有使用此方法的模块才会显示在列表中.
I am trying to setup a install feature for my modules, so I am trying to get it to load a list of directories and then check if the module file has a method called install. So only the modules with this method will be shown in the list.
到目前为止,这是我的代码:
Here is my code so far:
$output .= '<div id="module-dialog" title="Add Widget"><form id="widget-list" name="widget-list">
<select name="widgets" size="12" id="widgets-list">';
$dirHandler = opendir('modules') or die ("Could not open module folder");
while ($dir = readdir($dirHandler)) {
if($dir!="." && $dir!=".."){
// Code to filter out modules with install class -- goes here
$output .='<option>'.$dir.'</option>';
}
}
$output .='</select></form></div>';
模块文件名与目录名相同.例如:文件夹:Admin,文件:Admin.php
The module file name is the same as the directory name. example: folder:Admin, file:Admin.php
如果无法完成此操作,那么我想我将为安装功能创建一个单独的文件.
If this can not be done then I guess I will create a separate file just for the install function.
推荐答案
我假设您的意思是如何找出PHP文件是否定义了某个类?"
I assume you mean "How can I find out whether a PHP file defines a certain class?"
如果您可以包含要分析的每个PHP文件
这很容易:只需比较get_declared_classes()
在包含前后:
it's easy: Just compare the results of get_declared_classes()
before and after the inclusion:
$before = get_declared_classes();
include "myfile.php";
$after = get_declared_classes();
$new_classes = array_diff($before, $after);
print_r($new_classes); // Outputs all classes defined in myfile.php
如果您不能包含PHP文件 (例如,因为它们具有相同的类名)
If you can't include the PHP files (e.g. because they have the same class name)
这比较棘手.如果您想正确执行操作,请 令牌器功能 可以在PHP解析器级别分析文件.运行 token_get_all() 在文件上找到要查找的文件.
This is more tricky. If you want to do it right, the tokenizer functions can analyze a file on PHP parser level. Run a token_get_all() on your file to find out which one to look for.
如果您的类遵循简单的约定,仅使用正则表达式检查类类名"就足够了.
If your classes follow a simple convention, simply checking for "class classname" using a regular expression might be enough.
这篇关于类存在于外部文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!