ReflectionClass 一直返回 className does not exist

ReflectionClass keeps returning className does not exist

我想做的是使用 scandir() 扫描目录并获取那里的所有文件,然后使用 ReflectionClass 读取或访问 class.

我能够获取目录中的所有文件并将其分配给一个数组,但无法使用 \ReflectionClass 读取或访问 propertiesmethods 作为它不断返回

Class App\Controllers\AtController does not exist

这是我目前的代码

// 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

根据我的经验,这个问题通常有两个来源:

  1. 自动加载设置不正确;和
  2. class 文件中的 class 名称或命名空间有错别字。

如果这是第一期,在您的文件中添加一行即可解决问题:

<?php

$cur_dir = __DIR__;

// 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 = '';
$routeScript = '';

// Loop over the $classControllers
foreach($classControllers as $classController){
    if($classController != "." && $classController != "..")
    {
        include_once $classController; // <-- this line
        $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;
    }
}

请同时查看第二期。命名空间和 class 名称都区分大小写。两者很容易出现错别字:

<?php

namespace App\Controllers;

class AtController {
   // ...
}