Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
685 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...