I have a few general use functions that do not really make sense in any class as static methods. I would like to encapsulate them under a namespace so there are no conflicts with functions defined in the global scope. For my namespaced classes, I follow the widely-adopted pattern where a class such as \My\Namespaced\MyClass exists in My/Namespaced/MyClass.php on the include path.
Is there a best practice for where namespaced functions should be placed? Right now I'm putting them in "functions.php" within the directory holding classes under the same namespace. For example \My\Namespaced\myFunction exists in My/Namespaced/functions.php.
Also, is there any way to autoload these functions in the same way that classes are autoloaded?
Also, is there any way to autoload these functions in the same way that classes are autoloaded?
Not for global functions, but if ...
Is there a best practice for where namespaced functions should be placed?
I would consider using objects instead a "best practice", however we all know that it's not totally true.
There is no autoloading for global functions, you can encapsulate functions into classes as static functions and then the autoloader will kick into action. So that might be a suggestion, however you should be clear about the implications those static functions have for your overall design.
So to say: If you're okay with global functions, then you might be okay with global static class functions. They will break if you change a class's name (like with any global function name), you have however created something that can autoload and is compatible with your file naming scheme.
Edit: When I write global, I mean the fully qualified name of a function, that's the one starting with \
. See Name resolution rulesDocs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With