Prince Prince - 4 months ago 19
PHP Question

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.

Answer

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');