PHP: how to get variable from function in another

2019-09-10 04:19发布

问题:

This question already has an answer here:

  • Accessing a variable defined in a parent function 5 answers

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.

回答1:

function a() {
    $num = 1;
    function b($num) {
        echo $num;
    };
    b($num);
}
a();


回答2:

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.