Best practices for working with PHP names

I have several common usage functions that actually don't make sense in any class as static methods. I would like to encapsulate them in the namespace so that there are no conflicts with functions defined in the global scope. For my classes with names, I follow a widely accepted pattern in which a class exists such as \ My \ Namespaced \ MyClass in My / Namespaced / MyClass.php on the inclusion path.

Is there a best practice for posting functions with names? Right now I'm putting them in "functions.php" inside classes containing classes under the same namespace. For example, \ My \ Namespaced \ myFunction exists in My / Namespaced / functions.php.

Also, is there a way to autoload these functions in the same way that classes automatically load?

+6
source share
2 answers

Also, is there a way to autoload these functions in the same way that classes automatically load?

Not for global functions, but if ...

Is there a best practice for posting functions with names?

I would think about using objects instead of β€œbest practice,” however we all know that this is not entirely true.

There is no autoload for global functions, you can encapsulate functions in classes as static functions, and then the autoloader will take effect. So this may be a suggestion, however, you should clearly understand the implications that static functions have for your overall design.

So to speak: if you are in order with global functions, then you can be in order with global static functions of a class. They will be broken if you change the class name (for example, with any global function name), however, you created something that can automatically load and is compatible with your file naming scheme.

Edit: When I write global, I mean the full name of the function that starts with \ . See Doc Name Resolution Rules .

+5
source

Unfortunately, there is no autoload function for functions (because the PHP developers decided so ...), so you should think about how you include function files. For example, you can use functionality for this (for example, importFunction($namespace) ; it just maps the namespace to the file name and includes the file), or you can include every file containing functions immediately (at startup or the like).

+2
source

Source: https://habr.com/ru/post/896153/


All Articles