Accessing a variable defined in a parent function

2019-01-11 02:10发布

问题:

Is there a way to access $foo from within inner()?

function outer()
{
    $foo = "...";

    function inner()
    {
        // print $foo
    }

    inner();
}

outer();

回答1:

PHP<5.3 does not support closures, so you'd have to either pass $foo to inner() or make $foo global from within both outer() and inner() (BAD).

In PHP 5.3, you can do

function outer()
{
  $foo = "...";
  $inner = function() use ($foo)
  {
    print $foo;
  };
  $inner();
}
outer();
outer();



回答2:

Or am I missing something more complex you are trying to do?

function outer()
{
    $foo = "...";

    function inner($foo)
    {
        // print $foo
    }

    inner($foo);
}

outer();

edit Ok i think i see what you are trying to do. You can do this with classes using global, but not sure about this particular case



回答3:

I would like to mention that this is possibly not the best way to do coding, as you are defining a function within another. There is always a better option than doing in such a way.

function outer()
{
    global $foo;
    $foo = "Let us see and understand..."; // (Thanks @Emanuil)

    function inner()
    {
        global $foo;
        print $foo;
    }

    inner();
}

outer();

This will output:-

Let us see and understand...

Instead of writing this way, you could have written the folowing code snippet:-

function outer()
{
    $foo = "Let us see improved way...";

    inner($foo);

    print "\n";
    print $foo;
}

function inner($arg_foo)
{
    $arg_foo .= " and proper way...";
    print $arg_foo;
}

outer();

This last code snippet will output:-

Let us see improved way... and proper way...
Let us see improved way...

But at last, it is up to you always, as to which process you are going to use. So hope it helps.



回答4:

I know this can be done with classes, however with standalone functions I was sure you could not do a retrieval without setting a public/private variable.

But the only possible way that I can think of (not being experienced with this type of stuff) is passing $foo over to inner then doing the echo or print. :)



回答5:

I do not think it is possible.

PHP Manual has some comment around this and none of them seam to find a solution.

http://www.php.net/manual/en/language.variables.scope.php#77693

Another comment suggests that nested functions are not actually "nested" for real

http://www.php.net/manual/en/language.variables.scope.php#20407



标签: php scope