nested functions in php throws an exception when the outer is called more than once

前端 未结 5 665
执念已碎
执念已碎 2021-01-19 18:35

lest assume that i have the following

function a(){
  function b(){}
}
a(); //pass
a(); //error

why in the second call an exception is thr

相关标签:
5条回答
  • 2021-01-19 18:59

    It's exactly what is says, when you call a() again it tries to redeclare b(), declare b() outside of a() and call b() from within a() like so:

    function a() {
      b();
    }
    
    function b() {}
    
    a();
    a();
    
    0 讨论(0)
  • 2021-01-19 19:02

    Declaring a function within another function like that would be considered bad practice in php. If you really need a function inside a() you should create a closure.

    function a() {
      $b = function() {
    
      };
    }
    
    0 讨论(0)
  • 2021-01-19 19:15

    This is because when you execute function a it declares function b. Executing it again it re-declares it. You can fix this by using function_exists function.

    function a(){
      if(!function_exists('b')){
        function b(){}
      }
    }
    

    But what I suggest is, you should declare the function outside. NOT inside.

    0 讨论(0)
  • 2021-01-19 19:21

    It's because you're calling a() in a global scope. Add a function_exists call to make the above code work, but really there are few scenarios where you should really do something like this.

    0 讨论(0)
  • 2021-01-19 19:22

    Named functions are always global in PHP. You will therefore need to check if function B has already been created:

    function A() {
        if (!function_exists('B')) {
            function B() {}
        }
        B();
    }
    

    A different solution is to use an anonymous function (this will more likely fit your needs, as the function is now stored in a variable and therefore local to the function scope of A):

    function A() {
        $B = function() {};
        $B();
    }
    
    0 讨论(0)
提交回复
热议问题