Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Mark Baker:
Closure Binding as an alternative to “use” variables
Mar 13, 2017 @ 14:56:56

Mark Baker has posted a tutorial to his site showing how to use closure binding as an alternative to "use" when calling closures in your PHP application.

As a general rule when creating a Closure, arguments are passed when the function is called, but “use” variables (I’m sure that they have a formal name, but have no idea what it might be, so I just refer to them as “use” variables because they’re passed to the Closure through a “use” clause) are fixed as the value that they already contain when the Closure is defined, and the variables themselves must already exist within that scope

[...] Of course, the drawback of this approach is that when we need to change the price minimum and maximum values for filtering, they’re hard-coded in the callback.

He talks about the limits this imposes on calling the closure (ex: can't easily add addition params) and how the values have to already exist before the closure can be called. He points out that calling the variables by reference can help somewhat but it still comes with some of the same baggage. He then shows how to use object binding for a closure to handle the same kind of "min" and "max" by working around it with a closure bound internally to an object and called via a public method.

tagged: closure bind variable object tutorial use

Link: https://markbakeruk.net/2017/03/12/closure-binding-as-an-alternative-to-use-variables/


Trending Topics: