Anonymous FunctionsAlso called a closure function (closures allows you to create a function that is not specified, most often as the value of a callback function parameter. The closure function does not have a function name, and the defined variable is treated as a function directly when function () is passed into the variable.
$CL = function ($name) { returnsprintf (' Hello%s ', name);} echo $cli (' fuck ') '
Called directly by a variable name that is defined as an anonymous function.
echo Preg_replace_callback (' ~-([A-z] ~ ', function ($match) { returnstrtoupper ($match [1]);}, ' Hello-world '); ' Using the Use
$message = ' Hello '; $example = function () use ($message) {var_dump ($message);}; Echo $example ();//Output Hello$message = ' world ';//output Hello because the value of the inherited variable is when the function is defined and not when the function is called Echo $example ();/Reset to hello$ message= ' hello ';//refer to $example= function () use (& $message) {var_dump ($message);}; Echo $example ();//Output hello$message= ' world '; echo $example ();//Here the output world//closure function is also used for normal value $message= ' Hello '; $example = function ($data) use ($message) {return "{$data},{$message}";}; echo $example (' world '); example?
class cart{//defines constants in a class with the Const keyword, rather than the usual define () function. Constprice_butter = 1.00; Constprice_milk = 3.00; Constprice_eggs = 6.95; Protected$products = []; Publicfunction Add ($product, $quantity) {$this->products[$product] = $quantity; } publicfunction getquantity ($product) {//Did you define Returnisset ($this->products[$product])? $this->products[$prod Uct]:false; } publicfunction gettotal ($tax) {$total = 0.0; $callback = function ($quantity, $product) use ($tax, & $total) {//constant Returns the value of the constant//__class__ returns the class name $price = C Onstant (__class__. "::P rice_". Strtoupper ($product)); $total + = ($price * $quantity) * ($tax +1.0); }; The Array_walk () function applies a user-defined function to each element in an array. In the function, the key name and key value of the array are parameter Array_walk ($this->products, $callback); Callback anonymous function Returnround ($total, 2); }} $my _cart= new cart (); $my _cart->add (' Butter ', 1); $my _cart->add (' Milk ', 3); $my _cart->add (' eggs ', 6);p rint ( $my _cart->gettotal (0.05));