简体   繁体   English

PHP __autoload()与名称空间

[英]PHP __autoload() with namespace

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

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? 在名称空间Think \\下,我创建了上述注册函数,当我尝试使用未包含的类(如Storeage类)时,php应该会将Storeage作为变量传递给功能Think \\ Think :: autoload,但实际上已通过Think \\将Storeage作为变量,为什么将额外的Think \\添加到自动加载而不是仅仅添加Storeage?

Does that mean autoload will only search for classes which are declared under the same namespace where the autoload function is created? 这是否意味着自动加载将仅搜索在创建自动加载函数的相同名称空间下声明的类?

Autoload functions generally work by including files for you on demand. 自动加载功能通常通过按需包含文件来起作用。 So, for instance, I have a class called Spell in the namespace Write and it's in write/spell.php . 因此,例如,我在命名空间Write有一个名为Spell的类,它位于write/spell.php So I tell my autoload function how to find the file (in this case, my directories mirror my namespacing). 因此,我告诉我的自动加载功能如何查找文件(在这种情况下,我的目录镜像了我的命名空间)。

The autoload function itself doesn't care about namespaces per se. autoload函数本身并不关心名称空间。 It cares about finding the files that contain your class and loading them. 它关心查找包含您的类的文件并加载它们。 So, to answer your question, your autoload will only restrict itself to a namespace if you write the function to do that. 因此,为回答您的问题,如果您编写函数来执行此操作,则自动加载将仅将自身限制为名称空间。

Now, here's the caveat with the way you're doing it. 现在,这是您执行操作时的注意事项。 Your autoload function is already in a namespace. 您的自动加载功能已经在名称空间中。 That means you will have to manually include the file that contains that class or else your autoload will fail. 这意味着您将必须手动添加包含该类的文件,否则自动加载将失败。

Here is an example for you . 这是给你的例子。

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 . 如您所见,我们可以使用所需的任何名称空间,只需确保存在类文件的路径即可。

Hope this helps! 希望这可以帮助!

Best regards, Paul. 最好的问候,保罗。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM