PHP自动加载程序类
我正在实现一个autoloader类,但它不起作用。以下是autoloader类(灵感来源于): 正在命中自动加载函数,文件MyClass.class.php存在于include路径中,我可以通过将代码更改为:PHP自动加载程序类,php,spl-autoloader,Php,Spl Autoloader,我正在实现一个autoloader类,但它不起作用。以下是autoloader类(灵感来源于): 正在命中自动加载函数,文件MyClass.class.php存在于include路径中,我可以通过将代码更改为: <?php error_reporting(-1); ini_set('display_errors', 'On'); require_once __DIR__ . "/system/System.class.php"; require_once __DIR__ . "/syst
<?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)代码>返回对象,没有错误
有任何建议或指针吗?如上所述,在查找类文件之前,类名称的大小写应为小写
所以,解决方案1是将我的文件小写,这对我来说并不是一个可以接受的答案。我有一个名为MyClass的类,我想把它放在一个名为MyClass.class.php的文件中,而不是放在MyClass.class.php中
解决方案2是根本不使用spl_自动加载:
<?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";
}
}
?>
我建议您使用composer autoloader,您可以根据spl_autoload()的文档选择轻松使用其他软件包,该函数将类小写,因此它将查找myclass.class.php而不是myclass.class.php。如果我将我的文件名重命名为小写版本,它就可以正常工作。愚蠢的
/home/scott/www/system/
.class.php
MyClass
Fatal error: Class 'MyClass' not found in /home/scott/www/index.php on line 9
<?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);
?>
<?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";
}
}
?>