【问题标题】:Why do I have to re-include a class that was already included from a different file?为什么我必须重新包含已经从不同文件中包含的类?
【发布时间】:2015-03-29 03:48:53
【问题描述】:

我有类似以下的内容:

ma​​in.php:

spl_autoload_register(function($className) {
    require_once  $className . '.php';
});

use Example\RandomClass;

include 'anotherFile.php';

另一个文件.php:

RandomClass::example();

示例/RandomClass.php:

namespace Example;

class RandomClass {

    public static function example() {
        echo 'example';
    }

}

但是我收到以下警告: Warning: require_once(RandomClass.php): failed to open stream: No such file or directory in main.php on line 5 除非我在 anotherFile.php 中也有 use Example\RandomClass.php。这是预期的行为吗?我应该如何做到这一点,以便我只需要上课一次?

【问题讨论】:

标签: php namespaces include spl-autoload-register


【解决方案1】:

我认为你的自动加载是错误的:

require_once $className . '.php';

应该是

require_once 'Example\' . $className . '.php';

并检查 this answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2018-07-31
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多