【问题标题】:__autoload with namespace class gives fatal error for file not found带有命名空间类的 __autoload 为找不到文件提供致命错误
【发布时间】:2013-06-09 19:41:03
【问题描述】:

我正在使用 PHP 提供的 __autoload 功能。

不过这是index.php 我有:-

define('app_path', realpath('../'));

$paths = array(
        app_path, get_include_path());
set_include_path(implode(PATH_SEPARATOR, $paths));

function __autoload($classname)
{
    $filename = str_replace('\\', '/', $classname.'.php');
    require_once $filename;
}

use \engine\controllers as Controllers;

$data = new Controllers\base(); // This one is line no. 25 (Here is error)
echo $data->mind('Hi');

这个是我的base.php:-

 namespace controllers;
 class base {
    public function __construct() {
        echo __CLASS__ . '<br/>';
        echo __NAMESPACE__;
    }

    public function mind($myname)
    {
        echo $myname;
    }
 }

并抛出此错误:

我的目录结构如下:

app -&gt; engine -&gt; controller -&gt; base.php

app -&gt; index.php

我不确定发生了什么问题。我只是在学习如何使用namespace__autoload

我也试过spl_autoload_register,但没有成功。请建议。

编辑:1

另外,如果我想用 spl_autoload_register 替换它,如何实现。

【问题讨论】:

    标签: php class oop namespaces autoload


    【解决方案1】:

    不确定,但值得一试:

    在base.php中,在第1行更改为namespace engine\controllers;

    在 index.php 中,在第 23 行更改为 use engine\controllers as Controllers;(删除前导反斜杠)。

    【讨论】:

    • 天啊,亲爱的:*这就是为什么工程师是上帝出生的原因......你们可以闻到代码的每一个字母。
    • 另外,如果我想用spl_autoload_register 替换它,如何实现。
    猜你喜欢
    • 1970-01-01
    • 2012-04-20
    • 2017-05-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 2012-05-01
    相关资源
    最近更新 更多