PHP关闭破坏或我错过了什么? [英] Are PHP closures broken or am I missing something?

查看:92
本文介绍了PHP关闭破坏或我错过了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读PHP 5.3的新功能,其中一个主要功能是 closures

I've been reading on the new features of PHP 5.3, and one of the major features are closures.

非常严重的错误,PHP开发人员是:

a)混淆闭包只使用匿名函数

b)闭包在PHP 5.3.1中被破坏,其中我测试

Unless I'm very badly mistaken, the PHP developers are either:
a) confusing closures with just anonymous functions
b) the closures are broken in PHP 5.3.1 in which I'm testing

维基百科说的闭包是匿名函数加上函数的父范围变量到函数范围的绑定的机制。

From what wikipedia says closures are the mechanism of anonymous functions plus the binding of the function's parent's scope variables to the function's scope. The last part seems broken in PHP.

我已经检查过PHP错误,没有发现任何异常。

I've checked PHP bugs, and found nothing about this, strangely.

这里是我如何测试:

<?php

function getFun() {
    $x = 2;
    return function() {
        return $x;
    };
}
$f = getFun(); // getFun()(); doesn't work -.-
var_dump($f()); // $f() == null



在实际实现闭包的语言中,返回2: / p>

In languages that actually implement closures, it returns 2:

def f():
    x = 2
    return lambda: x
print(f()()) # prints 2

alert((function() {
    var x = 2;
    return function() {
        return x;
    };
})()()); // alerts 2

那么,我错了还是?

推荐答案

从外部范围继承的变量需要被明确列出。

variables inherited from the outer scope need to be listed explicitely. from the manual:

public function getTotal($tax)
{
    $total = 0.00;

    $callback =
        function ($quantity, $product) use ($tax, &$total)
...

这篇关于PHP关闭破坏或我错过了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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