名称空间自动加载不能正常工作


Namespaced autoloading not working properly

我在使用名称空间进行自动加载时遇到了麻烦。下面是我为此创建的目录结构:

index.php
app/
  utils/
    sys/
      DirReader.php
    helpers/
      DB.php

index.php包含自动加载器,其中包括文件DirReader.php和DB.php。

index.php是这样的:

<?php
function __autoload($ns_str) //ns_str = namespace string
{
    $path = str_replace('''', DIRECTORY_SEPARATOR, $ns_str);
    //echo "**$path**'n";
    require_once "$path.php";
}
use 'app'utils'sys as sys;
use 'app'utils'helpers as helpers;
$dir = new sys'DirReader();
$db = new helpers'DB();

这里是DirReader.php:

<?php
namespace app'utils'sys;
class DirReader
{
    public function __construct()
    {   
        echo "DirReader object created!'n";
    }   
}

这里是DB.php:

<?php
namespace app'utils'helpers;
class DB
{
    public function __construct()
    {   
        echo "DB object created!'n";
    }   
}

这个例子工作得很好,但是当我向index.php添加一个名称空间声明时,它失败了:

<?php
    namespace myns;
    function __autoload($ns_str) //ns_str = namespace string
    { /*. . .*/

PHP致命错误:类'app'utils'sys'DirReader'没有找到/var/www/html/php_learn/autoloading_1/index.php第15行PHP堆栈跟踪:PHP{主要}()/var/www/html/php_learn/autoloading_1/index . php: 0

根据我的说法,这个错误不应该出现,因为我在index.php中使用名称空间时使用了绝对名称。我知道说像use app'utils'sys as sys;这样的东西会失败,因为那么名称空间将相对于myns进行搜索,其中不存在任何东西。但我不知道为什么我的代码不工作。(我还尝试将index.php中的名称空间更改为autoloading_1,即包含目录的名称,但它没有帮助)。

__autoload函数必须在全局空间中定义。否则使用spl_autoload_register。不建议使用__autoload()