I'm trying to create an PHP object that can load objects in other files on demand when needed. My problem is that when I reference the files based on file location for the class definition, it can not find the files. So file structure:
/Test.php
/os/os.php (extends kernel)
/os/kernel.php
/os/libraries/lib1.php
/os/libraries/lib2.php
/os/libraries/lib3.php
In kernel.php, the libraries are referenced as 'libraries/lib1.php'. If I create an "os" object in Test.php. The lib files are not found.
Use a good naming convention for your classes, include_path and use spl_autoload.
For exemple:
Name your classes like this: class Os class Kernel class Libraries_Lib1 ...
Register your include path
set_include_path(implode(PATH_SEPARATOR, array(
realpath('os/'),
get_include_path(),
)));
spl_autoload_register("autoload");
And use an autoload:
function autoload($className) {
$name = implode("/", explode("_", $className));
require_once(strtolower($name) . ".php");
}
I think if you specify any sort of relative path (rather than just a filename or absolute path), PHP will try to include it relative to $_SERVER['SCRIPT_FILENAME']
(the main script which was run), and therefore you get inconsistent results.
You could define an absolute path somewhere in a file that you know will be always included , e.g.:
<?php
//e.g. this could be file os/kernel.php
//define absolute path to libraries dir
define('LIBRARY_PATH', dirname(__FILE__) . '/libraries');
And then elsewhere (in kernel.php and others) use this when you are including another file:
<?php
include LIBRARY_PATH . '/lib1.php';