Table of Contents
Anonymous function
Use syntax
More features of closure
Home Backend Development PHP Tutorial How to write closures in PHP+Swoole

How to write closures in PHP+Swoole

Oct 15, 2019 am 09:26 AM
swoole Closure

JS programmers always laugh at PHP for not having closures. Today I took the time to write an article to specifically introduce closures in PHP. PHP has added support for anonymous functions since version 5.3. After several versions and iterations to the current PHP5.6 and PHP7, the closure of the PHP language has been very complete. Combined with the event-driven support provided by Swoole, PHP's closure function is very powerful and elegant.

Anonymous function


The anonymous function is the core of the closure. The anonymous function in PHP is actually an object of the Closure class (please note that it is an object) . Different from ordinary object-oriented programming, the code of the anonymous function is written directly at the calling point. There is no need to write an additional class or write the code of the method. The advantage of this is that it is more direct. The following example sets a timer to output hello world every 2 seconds.

Traditional writing method

function timer () {
    echo "hello world";
}
Swoole\Timer::tick(2000, 'timer');
Copy after login

Closure writing method

Swoole\Timer::tick(2000, function () {
    echo "hello world";
});
Copy after login

Traditional writing method of non-closure, you must declare it first A function, and then enter the function name string. The two pieces of code are separated and not intuitive enough. The closure method writes the declaration of the timer and the code to be executed by the timer together, and the logic is very clear and intuitive. Using closure syntax makes it easy to write callback functions. In scenarios such as event-driven programming, sorting, array_walk, etc. that require users to pass in a piece of execution code, closures are written very elegantly.

The more powerful thing about closure is that it can introduce external variables directly at the call site. The method implemented in PHP is the use keyword.

Use syntax


If the timer just now needs to pass in a variable, the traditional writing method can only be achieved through global variables. Unlike JS, PHP's variable introduction is explicit. If you want to reference external variables, you must use use to declare them. JS is implicit, and external variables can be freely manipulated inside anonymous functions without declaration. The advantage of this is that you write less code, but the disadvantage is that it is risky and confusing.

Traditional writing method

$str = "hello world";
function timer () {
    global $str;
    echo $str;
}
Swoole\Timer::tick(2000, 'timer');
Copy after login

Closure writing method

$str = "hello world";
Swoole\Timer::tick(2000, function () use ($str) {
    echo $str;
});
Copy after login

The closure writing method uses use to directly introduce the current $str variable , without using global global variables. In addition, if you are in the event-driven programming mode of swoole, you cannot achieve asynchronous concurrency using global, because there is only one global global variable. If there are multiple client requests at the same time, each request must query the database and output different content. Traditional The programming method is not easy to implement. You need to use a global variable array to save the respective data with the client's ID as the KEY.

Traditional writing method

$requestArray = array();
$dbResultArray = array();
function my_request($request, $response) {
    global $dbResultArray, $requestArray;
    $queryId = $db->query($sql, 'get_result');
    $requestArray[$request->fd] = array($request, $response);
    $dbResultArray[$queryId] = $request->fd;
}
function get_result($queryId, $queryResult) {
    global $dbResultArray, $requestArray;
    list($request, $response) = $requestArray[$dbResultArray[$queryId]];
    $response->end($queryResult);
}
$server->on('request', 'my_request');
Copy after login

Closure writing method

$server->on('request', function ($request, $response) {
    $queryId = $db->query($sql, function ($queryId, $queryResult) use ($request, $response) {
        $response->end($queryResult);
    });
});
Copy after login

The traditional writing method is very complicated and needs to be repeated many times from the global array Save/extract data. The closure is written very concisely and elegantly, and it only takes a few lines of code to achieve the same function. Closure writing is very suitable for writing server programs in asynchronous non-blocking callback mode. Among the currently popular programming languages, only PHP and JS have this capability.

More features of closure


Use anonymous functions in class methods. Versions 5.4 and above do not need to use use to introduce $this, you can directly use anonymous functions Use $this in the function to call the method of the current object. In swoole programming, this feature can be used to reduce the use introduction and passing of the $serv object.

class Server extends Swoole\Server {
    function onReceive($serv, $fd, $reactorId, $data) {
        $db->query($sql, function ($queryId, $queryResult) use ($fd) {
            $this->send($fd, $queryResult);
        }
    }
}
Copy after login

In addition, if you want to modify external variables in the closure function, you can add the & reference symbol to the variable when using. Note that the object type does not need to be added, because in PHP objects are passed by reference instead of value by default.

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of How to write closures in PHP+Swoole. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

How to use swoole coroutine in laravel How to use swoole coroutine in laravel Apr 09, 2024 pm 06:48 PM

Using Swoole coroutines in Laravel can process a large number of requests concurrently. The advantages include: Concurrent processing: allows multiple requests to be processed at the same time. High performance: Based on the Linux epoll event mechanism, it processes requests efficiently. Low resource consumption: requires fewer server resources. Easy to integrate: Seamless integration with Laravel framework, simple to use.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

Which one is better, swoole or workerman? Which one is better, swoole or workerman? Apr 09, 2024 pm 07:00 PM

Swoole and Workerman are both high-performance PHP server frameworks. Known for its asynchronous processing, excellent performance, and scalability, Swoole is suitable for projects that need to handle a large number of concurrent requests and high throughput. Workerman offers the flexibility of both asynchronous and synchronous modes, with an intuitive API that is better suited for ease of use and projects that handle lower concurrency volumes.

Which one has better performance, swoole or java? Which one has better performance, swoole or java? Apr 09, 2024 pm 07:03 PM

Performance comparison: Throughput: Swoole has higher throughput thanks to its coroutine mechanism. Latency: Swoole's coroutine context switching has lower overhead and smaller latency. Memory consumption: Swoole's coroutines occupy less memory. Ease of use: Swoole provides an easier-to-use concurrent programming API.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

How is the swoole coroutine scheduled? How is the swoole coroutine scheduled? Apr 09, 2024 pm 07:06 PM

Swoole coroutine is a lightweight concurrency library that allows developers to write concurrent programs. The Swoole coroutine scheduling mechanism is based on the coroutine mode and event loop, using the coroutine stack to manage coroutine execution, and suspend them after the coroutine gives up control. The event loop handles IO and timer events. When the coroutine gives up control, it is suspended and returns to the event loop. When an event occurs, Swoole switches from the event loop to the pending coroutine, completing the switch by saving and loading the coroutine state. Coroutine scheduling uses a priority mechanism and supports suspend, sleep, and resume operations to flexibly control coroutine execution.

Chained calls and closures of PHP functions Chained calls and closures of PHP functions Apr 13, 2024 am 11:18 AM

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

See all articles