PHP __autoload() with namespace

不问归期 提交于 2019-12-08 11:42:38

问题


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?

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


回答1:


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. 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. 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.




回答2:


Here is an example for you .

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

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.



来源:https://stackoverflow.com/questions/21200010/php-autoload-with-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!