I have classes in a directory as follows:

database
- config
  - DB_Config.php
- ops
  - DB_Ops_User.php
  - DB_Ops_Communication.php
  - etc

I wrote a function to register all the classes in a directory:

private static function registerDirectories(array $directories)
{
   // If $directories is not null and not an array, it is an unexpected type.
   if(!is_array($directories)){
      if(!is_null){
         throw new InvalidArgumentException('$directories must be an array');
      }
      throw new InvalidArgumentException('$directories must be defined');
   }
   if(empty($directories)){
      throw new InvalidArgumentException('$directories must have at least one value');
   }

   $autoloadFunc = function($class) use ($directories)
   {
      foreach($directories as $directory)
      {
         $file = $class.'.php';
         if(file_exists($file))
         {
            require $file;
            return true;
         }
      }
      return false;
   };
   spl_autoload_register($autoloadFunc);
}

registerDirectories(['database/config', 'database/ops']);

However, I always get the error that class DB.php is not found. I've read that it tries to convert underscores to namespace directories. How are you supposed to work around this? I don't want to turn each underscore in my class names into a directory for readability purposes.

0 Answers