命名空间自动加载无法正常工作

时间:2015-10-07 09:52:23

标签: php

我在使用命名空间进行自动加载时遇到问题。这是我为此创建的目录结构:

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致命错误:类&#39; app \ utils \ sys \ DirReader&#39;找不到   第15行PHP堆栈上的/var/www/html/php_learn/autoloading_1/index.php   跟踪:PHP 1. {main}()   /var/www/html/php_learn/autoloading_1/index.php:0

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

1 个答案:

答案 0 :(得分:1)

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