【发布时间】:2020-09-09 02:23:15
【问题描述】:
我要做的是使用scandir() 扫描目录并获取那里的所有文件,然后使用ReflectionClass 读取或访问该类。
我能够获取目录中的所有文件并将其分配给一个数组,但无法使用\ReflectionClass 读取或访问methods 和methods,因为它不断返回
类 App\Controllers\AtController 不存在
这是我目前的代码
// The directory to scan and assign it to a variable
$classControllers = scandir($cur_dir . '/app/Controllers');
// Change to the ReflectionClass to access
chdir($cur_dir . '/app/Controllers/');
// Dump the $classControllers to see if it truly scan the directory
var_dump($classControllers);
$control = '';
// Loop over the $classControllers
foreach($classControllers as $classController){
if($classController != "." && $classController != "..")
{
$classController = str_ireplace(".php", "", $classController);
echo $classController . PHP_EOL;
// Use ReflectionClass to read the class name, methods and properties of each class.
$controllers = new \ReflectionClass("App\\Controllers\\$classController")#App\Controllers is the namespace of the files in the directory;
$controller = $controllers->getName();
$control = substr($controller, 12);
$control = ucfirst($control);
$routeScript .= "\t$control" . "," . PHP_EOL;
}
}
注意:new \ReflectionClass("App\\Controllers\\$classController"); #App\Controllers is the namespace of the files in the directory
【问题讨论】:
-
你是否使用自动加载来加载类?
-
是的,我使用自动加载来加载它
-
你是如何设置自动加载的?
-
尝试在
$classController = str_ireplace(".php", "", $classController);行前加include_once $classController;看看。 -
@KoalaYeung 我使用 composer.json 设置了自动加载
标签: php reflection php-7 php-7.2