I submitted a feature request to the PHP team today to fix a minor problem I’m having with templates then realized the full scope of what it would affect.
http://bugs.php.net/bug.php?id=52995
Basically, allow namespaces to be specified at include time. Consider
Page.php
class Page extends Controller {
}
Controller.php
class Controller {}
elsewhere in the code…
namespace MyNamespace;
new Page();
The autoloader looks for Page and includes it. Currently — CRASH. Why? Since the two class files don’t specify namespaces they attach to the global space. However - if what if we could attach them?
require('Page.php', '\\MyNamespace');
This would work. But it gets better. Say we give the autoloader a choice of Page php files, one default framework Page class and one in the Project. Again, we get a request for Page and we serve up the Project file - but wait… It starts like this
class Page extends \\Framework\\Page
The autoloader puts this into MyNamespace and then gets the request for this new class belonging to MyNamespace\Framework\Page (remember, the code is executing in a namespace set by the require statement). So it goes and gets the Framework page and puts it there.
The effects of this change can be tested in current PHP through a rotten trick with eval
eval('namespace '.$targetNamespace.'; '.file_get_contents('file.php'));
Due to the enormous performance hit I wouldn’t advise putting this into production, but it is a way to experiment with this concept.
I think this would open up a LOT of doors for code reuse. Course it could be the world’s worst idea. Comments?