Is it possible to access outer local variable in PHP? Is it possible to access outer local variable in PHP? php php

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.phpstring(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.


You can read default value by:

function(){    return preg_match(                     "yourVar = \d+"                   ,  str_file_get_contents(functionFile)                  ,   arrayToPutFieldsValue           ); }

If You would use two functons in the same time - it's like someone's using a spoon and You want to take a food from that spoon - You'll waste a food or some of You will starv.Anyway - You would have to set a pointer somehow in a hard way.It's impossible to get any field from other function or class without calling it to life.Functions/methods are instance-like - they need to be called.

Share the common fields by accessing a global fields with synchronized functions.