Alex Rivera | Logout

Accessing a variable defined in a parent function

Asked 2011-02-08T20:41:59.103
24

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

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

    function inner()
    {
        // print $foo
    }

    inner();
}

outer();
Edit
Report

2 Answers

55

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

answered 2011-02-08T20:52:10.173
0

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

answered 2011-02-08T20:51:56.453

Your Answer