In part 3rd of this series of articles (on how to develop valid PHP code in practice), Amol Hatwar discusses how to build the most efficient functional functions that do not sacrifice too much performance or manageability. The author focuses on how to write reusable functions and describes how to avoid some of the most common problems associated with the task.
Welcome back. In the 1th installment of this series, I discussed some basic PHP design rules and how to write safe, simple, platform-independent, and fast code. In the 2nd part, I introduced variables and discussed their use in PHP coding-good and bad practice.
In this article, you'll learn how to use functions wisely in PHP. In every high-level programming language, programmers can define functions, and PHP is no exception. The only difference is that you don't have to worry about the return type of the function.
In-depth study
Functions can be used to:
Encapsulates several lines of code into a single statement.
Simplify the code.
Most importantly, the application is a product of coordination with smaller applications.
The performance level of PHP is astonishing for developers who go from a compiled language, such as C + +, to PHP. User-defined functions are very expensive in terms of using CPU and memory resources. This is mainly because PHP is interpreted and loosely typed.
Packaging or not
Some developers wrap up every function they use simply because they don't like the name of the function, while others don't like to use the wrapper at all.
Wrapping existing PHP functions without adding or supplementing existing functionality is totally unacceptable. In addition to increasing size and execution time, such renaming functions can sometimes lead to management nightmares.
Inline functions in your code can lead to inexplicable code, even greater administrative disaster. The only benefit of doing this might be to get a faster code.
A more sensible approach is to define functions only if you need to use the code more than once, and you don't have built-in PHP functions available for the tasks you want to implement. You can choose to rename it or use it only if you want it to be restricted.
The chart in Figure 1 roughly shows the interrelationships between manageability and speed and the number of functions used. (I don't have a unit here, because numbers depend on the ability of the individual and the team; this relationship is important visual data.) )
Figure 1. Manageability/Speed Vs. Number of functions