What is php closure? What is the use? The following article will introduce you to php closures. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
What is a php closure?
PHP closure implementation mainly relies on anonymous functions
The anonymous function is passed in as a number in the ordinary function and can also be returned. This achieves a Simple closure.
In layman’s terms: child functions can use local variables in the parent function. This behavior is called closure!
Two holding points of closure:
1. As a reference to a function variable - when the function returns, it is active. ?
2. A Closure is a stack area that does not release resources when a function returns.
In fact, the above two points can be combined into one point, that is, when the closure function returns, the internal variables of the function are activated, and the stack area where the function is located Still retained.
What is the use of php closures?
Implementing PHP closure can not only read the variables inside the function, but also save the variables in the memory all the time, so that the variables will always exist even after the function is executed.
Several functions of closure:
1. Reduce foreach loop code
For example, manual The example in http://php.net/manual/en/functions.anonymous.php is Cart
<?php // 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。 // 其中有一个方法用来计算购物车中所有商品的总价格。该方法使用了一个closure作为回调函数。 class Cart { constPRICE_BUTTER = 1.00; constPRICE_MILK = 3.00; constPRICE_EGGS = 6.95; protected $products = array(); publicfunction add($product,$quantity) { $this->products[$product] =$quantity; } publicfunction getQuantity($product) { returnisset($this->products[$product]) ?$this->products[$product] : FALSE; } publicfunction 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); returnround($total, 2);; } } $my_cart= new Cart; // 往购物车里添加条目 $my_cart->add('butter', 1); $my_cart->add('milk', 3); $my_cart->add('eggs', 6); // 打出出总价格,其中有 5% 的销售税. print $my_cart->getTotal(0.05) . "\n"; // The result is 54.29 ?>
If we transform the getTotal function, we must use foreach
2, Reduce function parameters
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 that whether it is reading or using the code, it is better to use closures
3. Release the recursive function
<?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('error');};//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 n-1) and the function cannot be found (fib was not defined previously) Type)
So when you want to use a closure to cancel a loop function, you need to use a form like
<?php $recursive= function () use (&$recursive){ // The function is now available as $recursive }
4. About delayed binding
If you need to delay binding the variables in use, you need to use references, otherwise a copy will be made and placed in use when defining
<?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 and not using them The reference represents whether the value is assigned when calling or when the function is declared.
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of What is the use of php closures?. 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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

WebStorm Mac version
Useful JavaScript development tools
