Search code examples
phpclassautoload

User autoloader to include classes


I am having a directory which look like this:

Directory Schema

in the file inc/class/autoload.php, I have written a code to include automatically all the classes(Cart.class.php and Database.class.php).

autoload.php

<?php

spl_autoload_register('autoload');

function autoload($class){
    require_once($class.'.php');
}

The problem is that when I include the file inc/class/autoload.php in inc/templates/header.php or products/index.php, the class Cart.class.php and Database.class.php cannot be found.

To include the autoloader, I use:

  1. require_once('../inc/class/Database.class.php'); in products/index.php
  2. require_once('../class/Database.class.php'); in inc/templates/header.php

Kindly help me fix this problem.


Solution

  • Use this in autoload too include the files from the same location where your autoload.php is:

     require_once(dirname(__FILE__) . "/{$class}.class.php");
    

    and this only once in index.php

    require_once('../inc/class/autload.php');
    

    Each PHP script runs in the current location, so all files that are included, have the same working location. So if you call /products/index.php the working folder is /products. And with dirname(__FILE__) you get the current folder from the file that is calling the script. Here ../inc. For more Information lookup: Current Working Dir - How to change folder PHP? Absolute and Relativ Pathes in PHP.