我正在实现一个自动加载器类,但它不起作用。下面是autoloader类(受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";
}
}调用自动加载程序的代码如下:
<?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);
?>以及错误信息:
/home/scott/www/system/
.class.php
MyClass
Fatal error: Class 'MyClass' not found in /home/scott/www/index.php on line 9正在命中autoload函数,文件MyClass.class.php存在于包含路径中,我可以通过将代码更改为:
<?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);返回对象,没有错误。
有什么建议吗?
发布于 2014-07-11 19:11:03
正如在自拍上所述,类名在查找类文件之前是大小写的。
因此,解决方案1是将我的文件小写,这对我来说不是一个可接受的答案。我有一个名为MyClass的类,我想把它放在一个名为myclass.class.php而不是MyClass.class.php中的文件中。
解决方案2是根本不使用spl_autoload:
<?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";
}
}
?>https://stackoverflow.com/questions/24704431
复制相似问题