What use keyword do in closures in php

怎甘沉沦 提交于 2019-11-28 10:55:03

问题


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.


回答1:


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.




回答2:


Check this - http://php.net/manual/en/functions.anonymous.php, if an anonymous function wants to use local variables (for your code, it's $tax and $total), it should use use to reference them.



来源:https://stackoverflow.com/questions/10478596/what-use-keyword-do-in-closures-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!