spl_autoload fails when script ran from command line
I know this has to do with the path not being quite right but it has me baffled. I can run my script with no problems at all from the browser but when I do to the exact same spot from a shell, spl_autoload complains and dies:
Fatal error: spl_autoload(): Class db could not be loaded in...
I am using the absolute path from the root directory, echoe开发者_StackOverflow中文版d to screen and pasted it into a shell and verified that it is good. Please... what am I missing??
Try using the __DIR__
constant to locate the files, CLI PHP doesn't uses the same working dir.
Use something like this:
function __autoload($class)
{
require_once(dirname(__FILE__) . '/path/to/libraries/' . $class . '.php');
}
you can usually grab your root directory for the project with something along the lines of :
// The file that defines this is 2 directories below root, hence the ../ changes.
define('PATH_ROOT', realpath(dirname(__FILE__) . '/../../'));
Once you have your root path you can modify your include path, using set_include_path. (remember to include get_include_path when you set it otherwise you'll lose the defaults)
once thats sorted, just setup your autoloader assuming against the root dir and you should be fine, since its a bit more concrete than relying on relative paths which can change according to the working dir.
精彩评论