Detailed introduction to PHP closures (with code)
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
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
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
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); // 输出 吃米:米饭, 吃面:面条 吃米:甜粥, 吃面:馒头
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); // 输出 吃米:甜粥, 吃面:面条 吃米:甜粥, 吃面:花卷
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
