Home > Article > Backend Development > Let’s talk about the benefits of the official way of writing PHP closures
First, let’s learn about the officially explained PHP anonymous functions: https://www.php.net/manual/zh/functions.anonymous.php
php closure What are the benefits of official writing?
Specific problem description:
<?php class Cart { const PRICE_BUTTER = 1.00; const PRICE_MILK = 3.00; const PRICE_EGGS = 6.95; protected $products = array(); public function add($product, $quantity) { $this->products[$product] = $quantity; } public function getQuantity($product) { return isset($this->products[$product]) ? $this->products[$product] : FALSE; } public function getTotal($tax) { $total = 0.00; $callback = function ($quantity, $product) use ($tax, &$total) { $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); }; array_walk($this->products, $callback); return round($total, 2); } } $my_cart = new Cart; // 往购物车里添加条目 $my_cart->add('butter', 1); $my_cart->add('milk', 3); $my_cart->add('eggs', 6); // 打出出总价格,其中有 5% 的销售税. print $my_cart->getTotal(0.05) . "\n"; // 最后结果是 54.29 ?> Copy $callback = function ($quantity, $product) use ($tax, &$total) { $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); };
What is the difference between this code and foreach? Should the loop count and size be the same?
Answer:
can make the code more reusable and provide more possibilities for the functions provided.
For example, sorting is nothing more than comparing sizes, and then exchanging positions. The logic of exchanging positions is unified, but there are many situations when comparing sizes, so a closure callback will be provided so that the place where it is used can decide for itself. Who is older and who is younger.
The other is to make the code more readable through some basic methods.
For example, it should be more appropriate to change your example to array_reduce, so that others can probably realize what value you are trying to calculate into a single variable. But it’s best to write the closure function directly in the parameters.
For array traversal, in the early days, foreach had many problems, and improper use would create unnecessary bugs.
For example
// 这样用,可能会在后续的逻辑中出现bug foreach ($arr as &$item) { $item['ddd'] = 'ddd'; } // 这样用,就可以避免 array_walk($arr, function (&$item) { $item['ddd'] = 'ddd'; });
Anyway, there are pros and cons, and speed will of course have an impact.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Let’s talk about the benefits of the official way of writing PHP closures. For more information, please follow other related articles on the PHP Chinese website!