簡體   English   中英

PHP命名空間自動加載

[英]PHP Namespaces autoload

我有以下目錄結構:
/var/www/Project1/Project1.php
/var/www/Project1/User/UserProfile.php
在Project1.php內部:

<?php
namespace Project1;
set_include_path( __DIR__ );
spl_autoload_extensions('.php');
spl_autoload_register();

use User\UserProfile;

$u = new Avatar();
...

?>

內部UserProfile.php:

<?php    
namespace Project1\User;
class Avatar{
}
...
?>

當我執行php Project1.php我得到:

PHP致命錯誤:spl_autoload9():無法加載類User \\ UserProfile

我沒看到問題。

spl_autoload_register(); 當不帶參數調用時,將僅注冊默認的自動加載器,該加載器無法使用項目布局處理名稱空間。 您必須注冊自己的方法才能使其工作。 像這樣:

spl_autoload_register('my_autoload');

自動加載功能就在這里。 該函數期望類以如下方式存儲:

/path/to/project/Namespace/Classname.php
/path/to/project/Namespace/Subnamespace/Classname.php

您可以將類\\Namespaces\\Classname也可以使用舊風格的Namespace_Classname

function my_autoload ($classname) {
    // if the class where already loaded. should not happen
    if (class_exists($classname)) {
        return true;
    }   

    // Works for PEAR style class names and namespaced class names
    $path = str_replace(
        array('_', '\\'),
        '/',
        $classname
    ) . '.php';

   if (file_exists('/path/to/project/' . $tail)) {
        include_once 'path/to/project/' . $tail;
        return true;
    }   

    return false;
}   

請注意,該函數來自我的github包Jm_Autoloader 該軟件包提供了更多功能,包括多個包含路徑,路徑前綴和靜態自動加載(使用預定義的assoc數組類名稱=>文件名)。 如果願意,可以使用它;)

暫無
暫無

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

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