0

Example

function a(){
    $num = 1;

    function b(){
        echo $num; // how to get $num value?
    }
}

In this case global not working, because $num isn't global variable.

redexp
  • 4,765
  • 7
  • 25
  • 37
  • May I ask why you decided to define nested functions? – ಠ_ಠ Jul 25 '13 at 14:33
  • 1
    you can't. PHP has only two scopes. the current function scope, and the global scope. you can't access something from an intermediate scope, unless you're passing it around as an argument. – Marc B Jul 25 '13 at 14:36

2 Answers2

3
function a() {
    $num = 1;
    function b($num) {
        echo $num;
    };
    b($num);
}
a();
JohnnyFaldo
  • 4,121
  • 4
  • 19
  • 29
  • A function inside a function. That might not be the best idea. I'm going to have to get some info about this, im not sure this is a 'best practice' Edit: I've found this: http://stackoverflow.com/questions/415969/what-are-php-nested-functions-for – Martijn Jul 25 '13 at 14:37
  • If the plan was to always call b() from within a(), anonymous functions are a fine solution. – ಠ_ಠ Jul 25 '13 at 14:39
-3

You could use the S_SESSION to get the variable?

function a(){
    $_SESSION['num'] = 1;

    function b(){
        echo $_SESSION['num'];
    }
}

Not sure nested function is the way to go btw.

Morsok
  • 126
  • 1
  • 3
  • I dont recommend using session for this. It makes the SESSION var very large if you continue doing this, while there are perfectly acceptable (maybe even beter) methods to do this. – Martijn Jul 25 '13 at 14:40
  • It's true, but the code example was so small it's the only thing that occurred to me. – Morsok Jul 25 '13 at 14:41