4

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 ?

Hilmi
  • 3,411
  • 6
  • 27
  • 55
  • 3
    Please don't add a function in a function. It is almost never needed. – PeeHaa Aug 15 '12 at 10:53
  • possible duplicate of [How to define local functions in PHP?](http://stackoverflow.com/questions/7465451/how-to-define-local-functions-in-php) – kenorb May 18 '15 at 22:23

5 Answers5

7

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();
}
Niko
  • 26,516
  • 9
  • 93
  • 110
  • Thanks alot sir, but a question, after calling a() the first time can we access B() globally ? as you said "Named functions are always global" – Hilmi Aug 15 '12 at 11:14
  • With the first method, yes. The check `if(!function_exists('B'))` just prevents the re-declaration at the second call of A. With the second method, you're able to create an unnamed function that is not global (it is stored in a variable and therefore behaves the same way as other variables do). – Niko Aug 15 '12 at 11:21
4

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.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
1

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();
CKKiller
  • 1,424
  • 1
  • 16
  • 20
1

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() {

  };
}
xCander
  • 1,338
  • 8
  • 16
0

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.

Martin
  • 6,632
  • 4
  • 25
  • 28