微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/php/134510.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐