Load a class with a different name than the one passed to the autoloader as argument

巧了我就是萌 提交于 2019-12-11 05:29:56

问题


basically, I have the following problem: I want to make use of PHP's new namespace features. Unfortunately, I'm running a PHP version (5.3.2) in which namespace-autoload-support for linux still seems buggy and does not work (PHP should be able to load the class file automatically by its namespace without having to use a custom autoloader, but that doesn't work).

What I want to achieve is to write an autoloader that I can simply remove as soon as the php's namespace features work correctly (there seems to be a speed advantage when not using a custom autoloader) with having to change as less code as possible afterwards.

So I have a call like this:

$filereader = new system\libraries\file\XML();

which gets passed correctly as the string "system\libraries\file\XML" to my autoload-function. I can load the corresponding file "system/libraries/file/XML.class.php". However, the class in there will be named

class XML { ... }

(or something different than "system\libraries\file\XML") and so have a different name than the one by which PHP will try to load it. So is there an easy way to load that class ("XML") which has a different name than the name which I pass to the autoloader function? Can I perhaps do something in the autoloader to achieve that behaviour? (I'm using spl_autoload_register).

I know that even if it worked out I would still not be able to use all features of namespacing, since a (simple) autoloader would not respect the "use namespace" directive and I would still have to use rather long names for loading a class. However, if I understood PHP's namespace-features correctly, I could leave the code as it is when I later switch to using native namespace support instead of my autoloader.

If what I try to do does not make sense at all in your opinion or if I misunderstood namespaces, please tell me (- I have not used PHP's namespace features yet).


回答1:


I would load the file (which creates the XML class) and then alias the XML class to the properly namespaced system\libraries\file\XML class:

class_alias('XML', 'system\libraries\file\XML');

More generally:

class_alias(basename($class), $class));

Though I'm not quite sure whether class_alias can alias to namespaced classes...



来源:https://stackoverflow.com/questions/6161977/load-a-class-with-a-different-name-than-the-one-passed-to-the-autoloader-as-argu

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