php – 函数内具有函数的变量的范围?

Python中,您可以拥有以下内容
def foo(param1,param2):
    def bar():
        print param1 + param2
    bar()

我在PHP中遇到这种行为有些困难.
我希望这可以通过以下方式工作:

function foo($param1,$param2)
{
    function bar()
    {
        echo $param1 + $param2;
    }
    bar();
}

但那失败了.所以我读了一些关于闭包的内容(这被称为闭包不是吗?它是在Python中,我知道).在php documentation中关于匿名函数(他们说已经实现为闭包),他们告诉你以下列方式使用use()表达式:

function foo($param1,$param2)
{
    function bar() use($param1,$param2)
    {
        echo $param1 + $param2;
    }
    bar();
}

但那仍然失败.所以我把它改成了PHP-anonymous函数,就像这样:

function foo($param1,$param2)
{
    $bar = function() use($param1,$param2)
    {
        echo $param1 + $param2;
    };
    $bar();
}

这确实有效,但它看起来真的很难看.我错过了什么吗?我可以用任何方式改进吗?或者我只需要使用’丑陋’的方式?

(我不是在寻找关于闭包是否有用的讨论)

我找不到你链接到的手册页上的函数bar()使用($param1,$param2)语法,只是工作的“丑陋”版本(这是真正的匿名).我想你必须要用它.

在第二个例子中,bar不是闭包.要在PHP中创建一个闭包,你必须使用丑陋的用法,或者Closure class.每个函数都会创建自己的局部作用域,但闭包不是自动的.

PHP似乎对术语“闭包”有一个奇怪的定义,正如您在阅读manual时可能注意到的那样.它们将其定义为“匿名函数”的同义词:

Anonymous functions,also kNown as closures (…)

令人困惑,对吧?之后,如果要继承父作用域,他们会解释您需要use关键字:

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header.

PHP Wiki rfc page on closures给出了一些提示,说明为什么闭包以这种方式实现:

PHP’s notion of scope is quite different than the notion of scope other languages define. Combine this with variable variables ($$var) and it becomes clear that automatically detecting which variables from the outer scope are referenced inside are closure is impossible. Also,since for example global variables are not visible inside functions either by default,automatically making the parent scope available would break with the current language concept PHP follows.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...