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.

2
  • May I ask why you decided to define nested functions? Commented Jul 25, 2013 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. Commented Jul 25, 2013 at 14:36

2 Answers 2

3
function a() {
    $num = 1;
    function b($num) {
        echo $num;
    };
    b($num);
}
a();
Sign up to request clarification or add additional context in comments.

2 Comments

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: stackoverflow.com/questions/415969/…
If the plan was to always call b() from within a(), anonymous functions are a fine solution.
-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.

2 Comments

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.
It's true, but the code example was so small it's the only thing that occurred to me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.