Reputation: 1192
I am having a directory which look like this:
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:
require_once('../inc/class/Database.class.php');
in products/index.php
require_once('../class/Database.class.php');
in inc/templates/header.php
Kindly help me fix this problem.
Upvotes: 1
Views: 214
Reputation: 254
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.
Upvotes: 2