I am implementing an autoloader class and it's not working. Below is the autoloader class (inspired by this page on php.net):
class System
{
public static $loader;
public static function init()
{
if (self::$loader == NULL)
{
self::$loader = new self();
}
return self::$loader;
}
public function __construct()
{
spl_autoload_register(array($this, "autoload"));
}
public function autoload($_class)
{
set_include_path(__DIR__ . "/");
spl_autoload_extensions(".class.php");
spl_autoload($_class);
print get_include_path() . "<br>\n";
print spl_autoload_extensions() . "<br>\n";
print $_class . "<br>\n";
}
}
The code that invokes the autoloader is here:
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
require_once __DIR__ . "/system/System.class.php";
System::init();
$var = new MyClass(); // line 9
print_r($var);
?>
And the error messages:
/home/scott/www/system/
.class.php
MyClass
Fatal error: Class 'MyClass' not found in /home/scott/www/index.php on line 9
The autoload function is being hit, the file MyClass.class.php exists in the include path which I can verify by changing the code to this:
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
require_once __DIR__ . "/system/System.class.php";
require_once __DIR__ . "/system/MyClass.class.php";
System::init();
$var = new MyClass();
print_r($var);
?>
print_r($var);
returns the object and no errors.
Any advice or pointers?
As stated on the doc page for spl_autoload, the class name is lower cased before it looks for the class file.
So, solutions 1 is to lowercase my file, which is not really an acceptable answer for me. I have a class called MyClass, I want to put it in a file called MyClass.class.php not in myclass.class.php.
Solution 2 is to not use spl_autoload at all:
<?php
class System
{
public static $loader;
public static function init()
{
if (self::$loader == NULL)
{
self::$loader = new self();
}
return self::$loader;
}
public function __construct()
{
spl_autoload_register(array($this, "autoload"));
}
public function autoload($_class)
{
require_once __DIR__ . "/" . $_class . ".class.php";
}
}
?>