


Detailed explanation of PHP's closure (Closure) anonymous function, detailed explanation of closure function_PHP tutorial
Detailed explanation of PHP’s closure (Closure) anonymous function, detailed explanation of closure function
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, which connects closure and external variables.
$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.
/n";
};
$msg = "Hello, everybody";
callback($fun);
The result is: This is a closure use string value, msg is: Hello, everyone.
/n
In PHP’s new open 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 mini-applications are as follows:
/**
* A counter generator using closures
* This is actually based on the example of introducing closures in python...
* We can think about it this way:
* 1. Each time the counter function is called, a local variable $counter is created, initialized to 1.
* 2. Then create a closure, which generates a reference to the local variable $counter.
* 3. The function counter returns the created closure and destroys the local variable, but at this time there is a reference to $counter from the closure,
* It will not be recycled. Therefore, we can understand that the closure returned by the function counter carries a free
* Variable.
* 4. Since each call to counter creates an independent $counter and closure, the returned closures are independent of each other.
* 5. Execute the returned closure, increment the free state variable it carries and return it, and the result is a counter.
* Conclusion: This function can be used to generate independent counters.
*/
function counter() {
$counter = 1;
Return function() use(&$counter) {return $counter ++;};
}
$counter1 = counter();
$counter2 = counter();
echo "counter1: " . $counter1() . "
/n";
echo "counter1: " . $counter1() . "
/n";
echo "counter1: " . $counter1() . "
/n";
echo "counter1: " . $counter1() . "
/n";
echo "counter2: " . $counter2() . "
/n";
echo "counter2: " . $counter2() . "
/n";
echo "counter2: " . $counter2() . "
/n";
echo "counter2: " . $counter2() . "
/n";
?>
The role of closure
1. Reduce the code of foreach loop
For example, the example Cart in the manual http://php.net/manual/en/functions.anonymous.php
// A basic shopping cart, including some added items and the quantity of each item.
// One of the methods is used to calculate the total price of all items in the shopping cart. This method uses a closure as a callback function.
class Cart
{
const PRICE_BUTTER = 1.00;
const PRICE_MILK = 3.00;
const PRICE_EGGS = 6.95;
$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);
};
//Use user-defined function to perform callback processing on each element in the array
array_walk($this->products, $callback);
return round($total, 2);;
}
}
$my_cart = new Cart;
// Add items to shopping cart
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);
// Print the total price, including 5% sales tax.
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
function html($code , $id="", $class=""){
if ($id !== "") $id = " id = "$id"" ;
$class = ($class !== "")? " class ="$class">":">";
$open = " $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 it is better to use closures whether it is reading or using the code.
3. Unlock the recursive function
$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. fib(n-1) cannot find the 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
$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 references, otherwise a copy will be made and placed in use when defining
$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 a reference or not using a reference indicates whether the value is assigned when calling or when it is declared
Have you guys gained a new understanding of PHP’s anonymous functions, which are closure functions? I hope this article can give you some tips and I hope you like it.

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
