I would like to know if it is a good thing to define a function inside another function in PHP. Isn't it better to define it before the function (and not inside) in terms of performances.
You can also define a function within another function and logically this too should be a local variable but recall the rule that all functions are global. In PHP inner functions are global and hence behave in the same way as if they had been declared outside of any containing function.
There's nothing wrong with calling methods from other methods. In many designs, it's critical that you do this. This allows you to create subclasses that redefine the method, and the new definition will be called.
In general, variables in one function workspace are not available to other functions. However, nested functions can access and modify variables in the workspaces of the functions that contain them.
The included functions become nested within the functions above the call stack. Consider it in contrast to classes full of 100s of functions that weren't required upon every webservice call but could also have used the inbuilt lazy loading features of php.
I think you should care more about maintenability, and less about performance, especially in that kind of situation, where the difference in performances is probably not that big between the two solutions, while the difference in maintenability seems important.
Like Donald Knuth said :
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
This is quite true, in this situation ;-)
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