Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Function inside a Function. Good or bad?

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.

like image 562
Roch Avatar asked Sep 09 '09 10:09

Roch


People also ask

Can I put a function inside a function PHP?

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.

Is it bad to call a method in a method?

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.

Can a function contain a function?

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.

Does PHP support nested functions?

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.


1 Answers

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 ;-)

like image 74
Pascal MARTIN Avatar answered Oct 22 '22 22:10

Pascal MARTIN