duanhuayong6687 2012-05-07 07:57
浏览 66


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.

  • 写回答

2条回答 默认 最新

  • du958642589 2012-05-07 07:58

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 关于c++外部库文件宏的问题,求解
  • ¥15 office打开卡退(新电脑重装office系统后)
  • ¥300 FLUENT 火箭发动机燃烧EDC仿真
  • ¥15 【Hadoop 问题】Hadoop编译所遇问题hadoop-common: make failed with error code 2
  • ¥15 vb6.0+webbrowser无法加载某个网页求解
  • ¥15 RPA财务机器人采购付款流程
  • ¥15 计算机图形多边形及三次样条曲线绘制
  • ¥15 根据protues画的图用keil写程序
  • ¥200 如何使用postGis实现最短领规划?
  • ¥15 pyinstaller打包错误