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 o
There are multiple reasons against it:
<PHP 5.3
) or closures (>=PHP5.3
)That's a bad practice. Not only all weird things can happen and you'll lose too much time trying to debug it, but also the code becomes more confusing.
In terms of performance I'm not completely sure about it. All I know is that if you define a function inside another, that last function will only exist if the outer one is called. That may relief some memory. But I believe the payoff is not significant.
A very common way is to define the function outside of that function and call it inside.
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 ;-)
It depends on the situation, as it may be more desirable than using create_function()
. However you should know that the function which is created within the function is global in scope.
function creator() {
function inside() {
echo "hi.";
}
}
creator();
inside();
This will print "hi." even though the inside()
function was created "inside" of the creator function. So if you have a function in a loop which is creating a function, you need to check to see if the function exists, otherwise it will cause a function exists
error after the first loop.