Accessing a variable defined in a parent function

2019-01-11 01:56发布

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

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

    function inner()
    {
        // print $foo
    }

    inner();
}

outer();

标签: php scope
5条回答
手持菜刀,她持情操
2楼-- · 2019-01-11 02:16

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楼-- · 2019-01-11 02:18

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. :)

查看更多
▲ chillily
4楼-- · 2019-01-11 02:21

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.

查看更多
狗以群分
5楼-- · 2019-01-11 02:24

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();

查看更多
Deceive 欺骗
6楼-- · 2019-01-11 02:26

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

查看更多
登录 后发表回答