我在使用命名空间时遇到了问题。下面是我为此创建的目录结构:
index.php
app/
utils/
sys/
DirReader.php
helpers/
DB.phpindex.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致命错误:在第15行的/var/www/html/php_learn/autoloading_1/index.php中找不到类'app\utils\sys\DirReader‘:PHP1.main}() /var/www/html/php_learn/autoloading_1/index.php:0
根据我的看法,这个错误不应该出现,因为我在index.php中使用名称空间时使用了绝对名称。我知道说类似use app\utils\sys as sys;之类的话会失败,因为这样就会相对于myns搜索名称空间,在那里不存在任何东西。但我不知道为什么我的代码不起作用。(我还尝试将index.php中的命名空间名称更改为autoloading_1,即包含目录的名称,但没有帮助)。
发布于 2015-10-07 10:14:12
__autoload函数必须在全局空间中定义。否则使用寄存器。不鼓励使用__autoload()。
https://stackoverflow.com/questions/32989136
复制相似问题