Home > Backend Development > PHP Tutorial > Detailed introduction to PHP closures (with code)

Detailed introduction to PHP closures (with code)

不言
Release: 2023-04-05 19:58:01
forward
2439 people have browsed it

This article brings you a detailed introduction to PHP closures (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I have read many explanations about closures in PHP. Each document wants to express roughly the same meaning, but it is very difficult to understand. I describe it based on my own understanding. If you have a better understanding, please point it out

As we all know, everyone knows that the closure of PHP is function () use (){};

This article is divided into 3 steps:

1. Explain the closure Use
1: Use of use in closures - Part 1

function () use($param){};
$param = 1;
$data = function () use ($param)
{
    var_dump($param);    
};

$data();

$param = 2;
$data();

// 输出结果为
1
1
Copy after login

Analysis results: use The usage is equivalent to object (class usage), $data(), which means instantiation once. However, the language has the characteristics of text stream, the second time $data() There is no re-instance. The value obtained during the instance is 1, so the output result is the above result;

2: Use of use in the closure - Part 2

$param = 1;
$data = function () use ($param)
{
    var_dump($param);    
};

$data();

$param = 2;
$data = function () use ($param)
{
    var_dump($param);    
};
$data();

// 输出结果为
1
2
Copy after login

Analysis results : In the form of text stream, the variable is instantiated again, so the storage variable is 2, and the final output is 2;

3: The brackets after function() in the closure, the brackets before use Usage

function ($obj) use($param){};
    $param = 1;
    $data = function ($obj) use ($param)
    {
        var_dump($obj);
        var_dump($param);    
    };
    $data(2);
    
    $data(3);
    
    $param = 2;
    $data(4);
    // 输出
    2
    1
    
    3
    1
    
    4
    1
Copy after login

Analysis results: The brackets after function are equivalent to the usage of the function, each time the function is called It is the same as passing in data every time, and the use behind it means that the instance will not change after one time, so obj can change at any time.

2. Closure instance

Example 1:

    $arr = [
        '米' => ['咸粥', '甜粥', '米饭'], 
        '面' => ['面条', '花卷', '馒头'], 
    ];

    $param = '';
    $bag = function ($data) use ($param)
    {
        $l = count($data);
        return $data[rand(0, $l-1)];
    };

    $eat_arr = [];
    
    foreach ($arr as $key => $value) {
        $each_arr[] = '吃'.$key.':'.$bag($value);        
    }

    echo implode(',', $each_arr);
    
    // 输出
    吃米:米饭,  吃面:面条
    吃米:甜粥,  吃面:馒头
Copy after login

Example 2:

    $arr = [
        '米' => ['咸粥', '甜粥', '米饭'], 
        '面' => ['面条', '花卷', '馒头'], 
    ];

    $eat_arr = [];
    
    foreach ($arr as $key => $value) 
    {
        $bag = function () use ($value)
        {
            $l = count($value);
            return $value[rand(0, $l-1)];
        };

        $each_arr[] = '吃'.$key.':'.$bag();        
    }

    echo implode(',', $each_arr);
    // 输出
    吃米:甜粥, 吃面:面条
    吃米:甜粥, 吃面:花卷
Copy after login

3. Closure summary

Closure To sum up, the difference from the function is that an extra use intermediate value is added. When using it, please note that the () after function is a variable variable, and the variables in use() are instances after For variables that do not change, it is not very useful to write a closure in a loop, which is equivalent to instantiating it every time, so the closure can be written by defining a method before calling it.

The real difference between closures and functions:

Function: encapsulates multiple calls at once.
Closure: Only used by this method, the coupling degree is so low that it can be ignored.

The above is the detailed content of Detailed introduction to PHP closures (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.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