PHP __autoload()与名称空间 [英] PHP __autoload() with namespace

查看:101
本文介绍了PHP __autoload()与名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

spl_autoload_register('Think\Think::autoload');

在命名空间Think \下,我创建了上面的注册函数,当我尝试使用未包含的类(如Storeage类)时,php可能会将Storeage作为变量传递给功能Think \ Think :: autoload,但实际上传递了Think \ Storeage作为变量,为什么将额外的Think \添加到自动加载而不是仅添加Storeage?

Under namespace Think\ I created the above register function,when I try to use a class that has not been included like class Storeage,php will surposely pass Storeage as the variable to function Think\Think::autoload,but it actually passed Think\Storeage as the variable,why it adds the extra Think\ to the autoload instead of just Storeage?

这是否意味着自动加载将仅搜索在创建自动加载功能的同一个命名空间下声明的类?

Does that mean autoload will only search for classes which are declared under the same namespace where the autoload function is created?

推荐答案

以下是您的示例.

loader.php

loader.php

namespace bigpaulie\loader;

class Loader {

    /**
    *   DIRECTORY_SEPARATOR constatnt is predefined in PHP
    *   and it's different for each OS
    *   Windows : \
    *   Linux : /
    */
    public static function load($namespace){
        $filename = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . ".php";
        if(file_exists($filename)){
            require_once $filename;
        }else{
            throw new \Exception("Error Processing Request", 1);
        }
    }

}

index.php

index.php

require_once 'path/to/loader.php';

spl_autoload_register(__NAMESPACE__ . 'bigpaulie\loader\Loader::load');

$class1 = new \demos\Class1();

// or 

use bigpaulie\core\Class2;

$class2 = new Class2();

如您所见,我们可以使用所需的任何名称空间,只需确保类文件的路径存在.

as you can see we can use whatever namespace needed we just have to make sure that the path to the class file exists .

希望这会有所帮助!

最诚挚的问候, 保罗.

Best regards, Paul.

这篇关于PHP __autoload()与名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆