Search code examples
phprequirefile-existsspl-autoload-register

How to use file_exists with autoload


I'm trying to use the spl_autoload_register function to autoload my classes. I have got it to work but am still receiving a ton of warning messages like this: "Warning: include_once(application/models/controller.class.php): failed to open stream: No such file or directory in..."

I know I need to use file_exists method to fix this somehow but am not sure how to include this in my code:

    <?php

function myLoad($class) {
  include_once('application/controllers/'.$class.'.class.php');
  include_once('application/models/'.$class.'.class.php');
  include_once('application/'.$class.'.class.php');

}

spl_autoload_register('myLoad');

  new controller();


 ?>

I changed it to this and it is working now, but is there an easier/more concise way to do this? It seems sort of repetitive

function myLoad($class) {

  if (file_exists('application/controllers/'.$class.'.class.php')){
    include_once('application/controllers/'.$class.'.class.php');
  }
  if (file_exists('application/models/'.$class.'.class.php')){
    include_once('application/models/'.$class.'.class.php');
  }
  if (file_exists('application/'.$class.'.class.php')){
    include_once('application/'.$class.'.class.php');
  }
}

spl_autoload_register('myLoad');

Solution

  • To fix these kinds of problem I like to enumerate over an anonymous array:

    function myLoad($class) {
      foreach(['controllers', 'models', ''] as $prefix) {
        if(file_exists("application/$prefix/$class.class.php"))
          include_once("application/$prefix/$class.class.php");
      }
    }
    
    spl_autoload_register('myLoad');
    

    Note that if you put the string like that, you'll have a double slash for the case where there's no prefix, but that shouldn't make a difference. I find it more readable like that.