Classes can be autoloaded through spl_autoload. Functions cannot. This has lead to functions becoming increasingly 2nd class citizens. On the PHP dev list a proposal for PHP 5.4 has been made to allow autoloading of functions. However there are problems in the implementation and it remains to be seen if the RFC will settle down before last call for API changes and we go to 5.4 beta (I sort of doubt it will).
While discussing it yesterday I hit upon an elegant PHP 5.3 legal solution. Whenever you reference a class for the first time the existing autoload system will provide your autoload function with the fully qualified namespace path to the class. So you know implicitly that a namespace is about to get used.
So I thought to myself, if I was going to do namespace functions I would put them all in one file. Same with constants - to be honest likely the same file. So I thought, why can't the existing class autoload system handle the problem?
I don't think there's a reason it can't. Consider
- The class is requested. Say "MyNamespace\MyClass"
- The autoloader sees if there's a "MyNamespace/functions.php" file. If so, it calls require_once() on the file (PHP itself will track whether the file actually needs inclusion).
There are other ways to do this of course. It isn't foolproof of course, but it's highly unlikely in a primarily object-oriented system that a class method will call a function from a foreign namespace, and if it does there are still ways to handle this. One is to have the namespace file that defines the function itself call require for any files it depends on.