Class exists in an external file

拟墨画扇 提交于 2019-12-13 02:42:27

问题


How do I check an external file for a class?

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>';

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.


回答1:


I assume you mean "How can I find out whether a PHP file defines a certain class?"

If you can include each PHP files you want to analyze

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

If you can't include the PHP files (e.g. because they have the same class name)

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.



来源:https://stackoverflow.com/questions/2178284/class-exists-in-an-external-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!