Is it possible to access outer local variable in P

2020-01-31 01:22发布

问题:

Is it possible to access outer local varialbe in a PHP sub-function?

In below code, I want to access variable $l in inner function bar. Declaring $l as global $l in bar doesn't work.

function foo()
{
    $l = "xyz";

    function bar()
    {
        echo $l;
    }
    bar();
}
foo();

回答1:

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



回答2:

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.



回答3:

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.



标签: php scope