Test whether a file exists anywhere in the include path

后端 未结 5 2202
时光取名叫无心
时光取名叫无心 2021-02-20 12:25

I\'m writing an autoload function and in the inner logic of it would like to test whether a certain file exists somewhere in the path prior to including it.

This is the

5条回答
  •  清酒与你
    2021-02-20 12:50

    You should avoid the error supressor operator @.

    function autoload($class) {
       // Build path (here is an example).
       $path = DIR_CLASSES .
               strtollower(str_replace('_', DIRECTORY_SEPARATOR, $class)) .
               '.class.php';
    
       if (file_exists($path)) {
           include $path;
       }
    }
    
    spl_autoload_register('autoload'); 
    
    $front = new Controller_Front; 
    // Loads "application/classes/controller/front.class.php" for example.
    

    Update

    An important accent: I don't know where the file should be, I just want to know whether it exists in one of the directories in the include path. So I can't just do file_exists or something like this

    If your class could be in a number of directories, you could...

    • Have your autoload function traverse them all, looking for the class. I would not recommend this.
    • Rename your classes to have a name that easily maps to a file path, like in the example code above.

    If you do decide to traverse all folders looking for the class, and it becomes a bottleneck (benchmark it), you could benefit from caching the class name to file location mapping.

提交回复
热议问题