Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

lest assume that i have the following

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

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

cannot re-declare  function b()

i thought that each function call makes a new active record that it contains its own scope ; like in other languages other that PHP when we declare a variable in a function and called that function all the variables are alive for their scope, why the inner function is not the same ?

like image 356
Hilmi Avatar asked Dec 11 '22 23:12

Hilmi


2 Answers

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();
}
like image 182
Niko Avatar answered Feb 16 '23 01:02

Niko


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.

like image 39
Shiplu Mokaddim Avatar answered Feb 16 '23 01:02

Shiplu Mokaddim