什么使用关键字在php中关闭 [英] What use keyword do in closures in php

查看:146
本文介绍了什么使用关键字在php中关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ callback = function($ pricePerItem)use( $ tax,& $ total){
$ total + = $ pricePerItem *($ tax + 1.0);
};

php文档只说


'use'关键字也适用于闭包结构:

但没有解释它实际做了什么。

解决方案

它控制范围。在这种情况下,变量 $ tax $ total 在匿名函数之外声明。因为它们在使用条款中列出,所以它们可以从内部访问。



&符号使变量完全共享 - 例如,闭包内的变化将反映在外部范围内。在 $ tax 的情况下,变量是一个副本,所以不能在闭包中更改。



<大多数支持匿名函数的其他语言只会默认具有词法范围,但由于PHP已经有了其他范围规则,这会造成各种奇怪的情况,从而破坏了向后兼容性。作为一个度假胜地,这个 - 相当尴尬 - 解决方案已经到位。


I found code like this and can't find what it does

$callback = function ($pricePerItem) use ($tax, &$total) {
    $total += $pricePerItem * ($tax + 1.0);
};

php documentation only say

The 'use' keyword also applies to closure constructs:

but no explanation what it actually does.

解决方案

It controls the scope. In this case, the variables $tax and $total are declared outside of the anonymous function. Because they are listed in the use-clause, they are accessible from within.

The ampersand makes the variable fully shared - e.g. changes made within the closure will reflect in the outer scope. In the case of $tax, the variable is a copy, so can't be changed from within the closure.

Most other languages with support for anonymous functions would just per default have lexical scope, but since PHP already have other scoping rules, this would create all sorts of weird situations, breaking backwards compatibility. As a resort, this - rather awkward - solution was put in place.

这篇关于什么使用关键字在php中关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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