是否可以在PHP中访问外部局部变量? [英] Is it possible to access outer local variable in PHP?

查看:100
本文介绍了是否可以在PHP中访问外部局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在PHP子函数中访问外部局部变量?

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

在下面的代码中,我想访问内部功能栏中的变量$l.在bar中将$l声明为global $l无效.

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

推荐答案

您可能可以使用Closure来做到这一点...

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 :

  • 您必须在函数的声明后加上;
  • 您可以通过引用use将该变量命名为use (& $l)
  • ,并在其前加上&.
  • 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

这篇关于是否可以在PHP中访问外部局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆