簡體   English   中英

PHP自動加載器類

[英]PHP Autoloader Class

我正在實現一個自動加載器類,它無法正常工作。 下面是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

自動加載功能被命中,文件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); 返回對象,沒有錯誤。

有什么建議或指示嗎?

如在spl_autoloaddoc頁面上所述,在查找類文件之前,類名是小寫的。

因此,解決方案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";
    }
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM