开发者

PHP namespaced function best practices

开发者 https://www.devze.com 2023-03-31 18:56 出处:网络
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

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


Unfortunately there is no autoloading for functions (because the PHP devs decided so...), thus you must think about, how you get the function files include. For example you can use a functional for that (like importFunction($namespace); It would just map the namespace against the filename and include the file), or you can include every file, that contains functions at once (at startup or such).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号