What use keyword do in closures in php

后端 未结 2 1543
太阳男子
太阳男子 2020-12-21 23:17

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

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


        
相关标签:
2条回答
  • 2020-12-21 23:23

    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.

    0 讨论(0)
  • 2020-12-21 23:41

    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.

    0 讨论(0)
提交回复
热议问题