PHP - Function inside a Function. Good or bad?

后端 未结 4 1451
有刺的猬
有刺的猬 2020-12-30 01:41

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

相关标签:
4条回答
  • 2020-12-30 01:59

    There are multiple reasons against it:

    • The documentation of the inner function will not be parsed.
    • The inner function only exists after the outer function has been called (but even outside the scope of the outer function afterwards)
    • It is hard to read (because it is not seen commonly)
    • The only advantage I could think of is defining a callback, but this is better done with create_function() (<PHP 5.3) or closures (>=PHP5.3)
    • If you're concerned about performance on this level, you should really be using another language
    0 讨论(0)
  • 2020-12-30 02:02

    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.

    0 讨论(0)
  • 2020-12-30 02:11

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

    0 讨论(0)
  • 2020-12-30 02:14

    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.

    0 讨论(0)
提交回复
热议问题