1

I'm sorry if this has been answered before - I searched but couldn't find a definitive answer.

If I have a function foo() that deals with a variable $x, and then a subfunction bar(), how can I access $x?

function foo(){       

    $x = 0;

    function bar(){

        //do something with $x

    }

}

Is this code correct, or is there better practice for accessing the variables in a parent function?

Ben
  • 8,696
  • 7
  • 37
  • 72

2 Answers2

1

Please note for using global variable in child functions:

This won't work correctly...

<?php 
function foo(){ 
    $f_a = 'a'; 

    function bar(){ 
        global $f_a; 
        echo '"f_a" in BAR is: ' . $f_a . '<br />';  // doesn't work, var is empty! 
    } 

    bar(); 
    echo '"f_a" in FOO is: ' . $f_a . '<br />'; 
} 
?> 

This will...

<?php 
function foo(){ 
    global $f_a;   // <- Notice to this 
    $f_a = 'a'; 

    function bar(){ 
        global $f_a; 
        echo '"f_a" in BAR is: ' . $f_a . '<br />';  // work!, var is 'a' 
    } 

    bar(); 
    echo '"f_a" in FOO is: ' . $f_a . '<br />'; 
} 
?>

For more read here http://php.net/manual/en/language.variables.scope.php there is disadvantages of global variables in php so please read it from here Are global variables in PHP considered bad practice? If so, why?

Community
  • 1
  • 1
Ankur Tiwari
  • 2,627
  • 2
  • 17
  • 39
  • I understood that using `global` is very bad practice. Is this true? And do you need to declare `global` when both initiating the variable *and* accessing it? – Ben Aug 12 '15 at 09:09
  • 1
    Yes, both times. And it's not necessarily bad as it's prone to errors. If you use global you won't know what function changed what variable, since there can be serveral functions that use the same global variable. Long story short it makes debugging really hard. – Andrei Aug 12 '15 at 09:22
0

You can either pass it as a parameter like this:

function foo(){       

    $x = 0;

    function bar($x){

        //Do something with $x;

    }

    bar($x);

}

Or you can create a closure:

function foo(){       

    $x = 0;

    $bar = function() use ($x) {

        //Do something with x
    };

    $bar();

}
Daan
  • 11,291
  • 6
  • 26
  • 47