簡體   English   中英

每個人的意思是:“ spl:_autoload()是__autoload()的默認實現”

[英]What does everyone mean by: 'spl:_autoload() is default implementation of __autoload()'

我對php自動加載的東西感到困惑: spl_autoload()函數。 在每個答案中,我發現此函數是__autoload默認實現。 PHP是否不應該自己定義__autoload()默認實現,然后如果我顯式創建__autoload() ,它將覆蓋它?

如果我沒有在我的PHP文件中明確定義__autoload()函數,是否將使用默認實現? spl_autoload()某種內部函數,如果可以,為什么在php doc中呢?

(如果它不是內部函數)在每spl_autoload()比如有沒有這個功能的任何調用,只有spl_autoload_register不帶任何參數, spl_autoload_extensions等。 為什么這樣? 我想念什么?

引用自: 什么是自動加載; 如何使用spl_autoload,__ autoload和spl_autoload_register?

 set_include_path(get_include_path().PATH_SEPARATOR.'path/to/my/directory/'); spl_autoload_extensions('.php, .inc'); spl_autoload_register(); 

由於spl_autoload是__autoload()魔術方法的默認實現,因此,當您嘗試實例化新類時,PHP將調用spl_autoload。

因此,如果我不調用spl_autoload_register() ,它將不會注冊默認實現? spl_autoload是否spl_autoload查看由spl_autoload_extensions();設置的擴展名spl_autoload_extensions(); 然后從包含路徑導入具有這些擴展名的所有文件? 重復前面提到的問題: spl_autoload()內部函數嗎?

我知道__autoload()已過時,我應該使用spl_autoload_register() 我只想確保我知道所有工作原理。

謝謝。

重復前面提到的問題: spl_autoload()內部函數嗎?

如果您不傳遞參數,那只是spl_autoload_register的“默認值”。 如果需要,您也可以獨立調用此函數。 可以使用spl_autoload_extensionsset_include_path配置spl_autoload_extensions set_include_path

在內部, spl_autoload將完整的合格類名稱(fqcn)作為查找類實現的路徑。 (也許用字符串替換目錄分隔符)。 之后,它將在給定文件之后搜索class_include_path的每個元素。

spl_autoload_extensions(".php");
spl_autoload_register();
$foo = new \foo\Bar();
// now spl_autoload tries to load the file foo/Bar.php inside your class path.

如果您需要更復雜的內容,則必須為自動加載器創建自己的回調。 即像這樣

spl_autoload_register(function($class) {
    $path = 'classes' . DIRECTORY_SEPERATOR;
    // dont care about case
    $class = strtolower($class);
    // replace _ with DIRECTORY_SEPERATOR
    $name = str_replace('_', DIRECTORY_SEPERATOR, $class);
    // don't care about windows/unix
    $name = str_replace('/', DIRECTORY_SEPERATOR, $name);
    $file = $path . $name . '.php';
    if (file_exists($file)) {
        include ($file);
    }
});

注意:上面的示例並不關心spl_autoload_extensionsset_include_path的值。

暫無
暫無

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

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