Advantages and disadvantages of php closures

(*-*)浩
Release: 2023-02-23 15:22:01
Original
3662 people have browsed it

Advantages and disadvantages of php closures

Closure function: Temporarily create a function without a name, often used as a callback function. (Recommended learning: PHP video tutorial)

In layman’s terms: child functions can use local variables in the parent function. This behavior is called closure.

Anonymous function assignment

$demo=function($str){
   echo $str;
 }
 $demo('hello,world');
Copy after login

Closures can inherit variables from the parent scope, and any variables of this type should be passed in using the use language structure.

$message='hello';
 $example=function() use ($message){
   var_dump($message);
 };
 echo $example();
Copy after login

Advantages of closure:

Can read variables inside the function;

Let these variables always exist in memory and will not be recycled by the garbage collection mechanism after the call is completed

Disadvantages of closures:

As the saying goes, the opposite is true. Since closures will save the variables in the function in memory and consume a lot of memory, closures cannot be abused. The solution is to delete unused local variables before exiting the function.

The above is the detailed content of Advantages and disadvantages of php closures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template