Home>Article>Backend Development> Advantages and disadvantages of php closures

Advantages and disadvantages of php closures

(*-*)浩
(*-*)浩 Original
2019-09-04 09:22:08 3600browse

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

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

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!

Statement:
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