Is it possible to access outer local variable in PHP?

You could probably use a Closure, to do just that...


Edit : took some time to remember the syntax, but here's what it would look like :

function foo()
{
    $l = "xyz";
    $bar = function () use ($l)
    {
        var_dump($l);
    };
    $bar();
}
foo();

And, running the script, you'd get :

$ php temp.php
string(3) "xyz"


A couple of note :

  • You must put a ; after the function's declaration !
  • You could use the variable by reference, with a & before it's name : use (& $l)

For more informations, as a reference, you can take a look at this page in the manual : Anonymous functions


You must use the use keyword.

$bar = function() use(&$l) {
};
$bar();

In the very very old PHP 5.2 and earlier this didn't work. The syntax you've got isn't a closure, but a definition of a global function.

function foo() { function bar() { } }

works the same as:

function foo() { include "file_with_function_bar.php"; }

If you execute function foo twice, PHP will complain that you've tried to re-define a (global) function bar.

Tags:

Php

Scope