Let's talk about the benefits of the official way of writing PHP closures

藏色散人
Release: 2023-04-10 20:52:02
forward
3985 people have browsed it

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(&#39;butter&#39;, 1);
$my_cart->add(&#39;milk&#39;, 3);
$my_cart->add(&#39;eggs&#39;, 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);
            };
Copy after login

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[&#39;ddd&#39;] = &#39;ddd&#39;;
}
// 这样用,就可以避免
array_walk($arr, function (&$item) {
   $item[&#39;ddd&#39;] = &#39;ddd&#39;;
});
Copy after login

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!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!