Nested functions in php throw an exception when an external call is called more than once

Suppose i have

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

why in the second call an exception is thrown and he says

 cannot re-declare function b() 

I thought that every function call makes a new active record, that it contains its own scope; as in other languages, others that PHP, when we declare a variable in a function and call this function, all variables are live for their scope, why is the inner function not the same?

+4
source share
5 answers

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

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

Another solution is to use an anonymous function (this will most likely meet your needs, since the function is now stored in a variable and therefore local to function area A):

 function A() { $B = function() {}; $B(); } 
+7
source

This is because when you execute function a , it declares function b. Performing it again, he reiterates this. You can fix this using function_exists function_exists .

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

But I suggest you should declare a function outside. NOT inside.

+4
source

This is what is said when you call a() again, it tries to update b() , declare b() outside a() and call b() from a() like this:

 function a() { b(); } function b() {} a(); a(); 
+1
source

Declaring a function inside another function like this will be considered bad practice in php. If you really need a function inside (), you must create a closure.

 function a() { $b = function() { }; } 
+1
source

This is because you are calling a() in the global scope. Add a function_exists call to make the above code, but there are actually a few scripts in which you really have to do something like this.

0
source

All Articles