Home Backend Development PHP Tutorial PHP closure anonymous function diagram

PHP closure anonymous function diagram

Jun 13, 2018 am 11:01 AM
php anonymous function Closure

This article mainly introduces to you the PHP anonymous function introduced in php5.3, that is, closure (Closure), and the role of closure. It is very detailed. It is recommended here to friends in need.

php's closure (Closure) is an anonymous function, which was introduced in PHP5.3.

The syntax of closure is very simple. The only keyword that needs attention is use. Use is to connect the closure and external variables.

The code is as follows:

$a = function() use($b) {}

A simple example is as follows:

function callback($fun) {
$fun();
}
$msg = "Hello, everyone";
$fun = function () use($msg) {
print "This is a closure use string value, msg is: $msg. <br />/n";
};
$msg = "Hello, everybody";
callback($fun);

The result is: This is a closure use string value, msg is: Hello, everyone.

In PHP's newly opened closure syntax, we use use to use variables defined outside the closure. Here we use the external variable $msg. After it is defined, its value is changed. After the closure is executed, the original value is output. For basic type parameters passed by value, the value of the closure use is determined when the closure is created.

The small application is as follows:

/** 
 * 一个利用闭包的计数器产生器 
 * 这里其实借鉴的是python中介绍闭包时的例子... 
 * 我们可以这样考虑: 
 *      1. counter函数每次调用, 创建一个局部变量$counter, 初始化为1. 
 *      2. 然后创建一个闭包, 闭包产生了对局部变量$counter的引用. 
 *      3. 函数counter返回创建的闭包, 并销毁局部变量, 但此时有闭包对$counter的引用,  
 *          它并不会被回收, 因此, 我们可以这样理解, 被函数counter返回的闭包, 携带了一个游离态的 
 *          变量. 
 *      4. 由于每次调用counter都会创建独立的$counter和闭包, 因此返回的闭包相互之间是独立的. 
 *      5. 执行被返回的闭包, 对其携带的游离态变量自增并返回, 得到的就是一个计数器. 
 * 结论: 此函数可以用来生成相互独立的计数器. 
 */  
function counter() {  
    $counter = 1;  
    return function() use(&$counter) {return $counter ++;};  
}  
$counter1 = counter();  
$counter2 = counter();  
echo "counter1: " . $counter1() . "<br />/n";  
echo "counter1: " . $counter1() . "<br />/n";  
echo "counter1: " . $counter1() . "<br />/n";  
echo "counter1: " . $counter1() . "<br />/n";  
echo "counter2: " . $counter2() . "<br />/n";  
echo "counter2: " . $counter2() . "<br />/n";  
echo "counter2: " . $counter2() . "<br />/n";  
echo "counter2: " . $counter2() . "<br />/n";  
?>

The role of closure

1. Reduce the code of foreach loopFor example, manual http The code of the example Cart

in ://php.net/manual/en/functions.anonymous.php is as follows:

<?php
// 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。
// 其中有一个方法用来计算购物车中所有商品的总价格。该方法使用了一个closure作为回调函数。
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";
// The result is 54.29
?>

If we transform the getTotal function here, we must use foreach.

2. Reduce function parameters

The code is as follows:

function html($code , $id="", $class=""){
if ($id !== "") $id = " id = \"$id\"" ;
$class = ($class !== "")? " class =\"$class\">":">";
$open = "<$code$id$class";
$close = "</$code>";
return function ($inner = "") use ($open, $close){
return "$open$inner$close";
    };
}

If we use the usual method, we will put inner into the html function parameters , so whether it is code reading or use, it is better to use closures.

3. Unlock the recursive function

The code is as follows:

<?php
$fib = function($n) use(&$fib) {
    if($n == 0 || $n == 1) return 1;
    return $fib($n - 1) + $fib($n - 2);
};
echo $fib(2) . "\n"; // 2
$lie = $fib;
$fib = function(){die(&#39;error&#39;);};//rewrite $fib variable 
echo $lie(5); // error   because $fib is referenced by closure

Note that use in the above question uses &. If & is not used here, an error will occur. fib(n-1) cannot find function (the type of fib was not defined previously)

So when you want to use closure to cancel the loop function, you need to use

The code is as follows:

<?php
$recursive = function () use (&$recursive){
// The function is now available as $recursive
}

This form.

4. Delay binding

If you need to delay binding the variables in use, you need to use a reference, otherwise a copy will be made when defining Copy it to use

The code is as follows:

<?php
$result = 0;
$one = function()
{
    var_dump($result);
};
$two = function() use ($result)
{
    var_dump($result);
};
$three = function() use (&$result)
{
    var_dump($result);
};
$result++;
$one();    // outputs NULL: $result is not in scope
$two();    // outputs int(0): $result was copied
$three();    // outputs int(1)

Using references or not using references means assigning values ​​when calling or assigning values ​​when declaring

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Mysql operation buffer method in php

Definition and usage of mail function in php

Definition and usage of mail function in php

The above is the detailed content of PHP closure anonymous function diagram. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 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)

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

PHP integrated AI intelligent picture recognition PHP visual content automatic labeling PHP integrated AI intelligent picture recognition PHP visual content automatic labeling Jul 25, 2025 pm 05:42 PM

The core idea of integrating AI visual understanding capabilities into PHP applications is to use the third-party AI visual service API, which is responsible for uploading images, sending requests, receiving and parsing JSON results, and storing tags into the database; 2. Automatic image tagging can significantly improve efficiency, enhance content searchability, optimize management and recommendation, and change visual content from "dead data" to "live data"; 3. Selecting AI services requires comprehensive judgments based on functional matching, accuracy, cost, ease of use, regional delay and data compliance, and it is recommended to start from general services such as Google CloudVision; 4. Common challenges include network timeout, key security, error processing, image format limitation, cost control, asynchronous processing requirements and AI recognition accuracy issues.

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

How to use PHP to develop AI-driven advertising delivery PHP advertising performance optimization solution How to use PHP to develop AI-driven advertising delivery PHP advertising performance optimization solution Jul 25, 2025 pm 06:12 PM

PHP provides an input basis for AI models by collecting user data (such as browsing history, geographical location) and pre-processing; 2. Use curl or gRPC to connect with AI models to obtain click-through rate and conversion rate prediction results; 3. Dynamically adjust advertising display frequency, target population and other strategies based on predictions; 4. Test different advertising variants through A/B and record data, and combine statistical analysis to optimize the effect; 5. Use PHP to monitor traffic sources and user behaviors and integrate with third-party APIs such as GoogleAds to achieve automated delivery and continuous feedback optimization, ultimately improving CTR and CVR and reducing CPC, and fully implementing the closed loop of AI-driven advertising system.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

See all articles