Use keyword in functions – PHP [duplicate]

The use of “use” is correct in this case too.

With closures, to access variables that are outside of the context of the function you need to explicitly grant permission to the function using the use function. What it means in this case is that you’re granting the function access to the $tax and $total variables.

You’ll noticed that $tax was passed as a parameter of the getTotal function while $total was set just above the line where the closure is defined.

Another thing to point out is that $tax is passed as a copy while $total is passed by reference (by appending the & sign in front). Passing by reference allows the closure to modify the value of the variable. Any changes to the value of $tax in this case will only be effective within the closure while the real value of $total.

Leave a Comment