Home  >  Article  >  Backend Development  >  Closures in PHP

Closures in PHP

山海
山海forward
2019-09-19 17:30:113869browse

What is closure? A closure is a function that can read the internal variables of other functions. For example, in JavaScript, only subfunctions inside a function can read local variables, so closures can be understood as "functions defined inside a function." In essence, closures are the bridge that connects the inside of a function with the outside of the function. This article focuses on closures in PHP.

Closures in PHP

1. The closure function is also called an anonymous function. It is a function without a specified name and is generally used in the callback part.

2. The closure is used as a callback Basic usage, echo preg_replace_callback('~-([a-z])~', function ($match) {

return strtoupper($match[1]);

} , 'hello-world');

The third parameter is the target string to be matched, and the second parameter is an anonymous function. When preg_replace_callback is executed, the anonymous function will be called back and the matching The result is passed as a parameter of the anonymous function

3. Use of closure function variable assignment $greet = function($name)
{ printf("Hello %s\r\n", $name);
};$greet('World');
The closure function is assigned to a variable. This variable is directly followed by () parentheses to execute the function. The parameters in the parentheses will be passed to Go inside the closure function

4. The closure function inherits the use of variables from the parent scope $message = 'hello';$example = function () use ($message) {                         var_dump($message);
};$example();
Use the use keyword to pass the variables of the parent scope outside the function into the function 5. Closure function variable assignment () executes the function to pass parameters use() keyword Pass the parent function Domain variable $message="taoshihan";$example = function ($arg) use ($message) { var_dump($arg . ' ' . $message);
};$example("hello"); // Output string(15) "hello taoshihan"

The above is the detailed content of Closures in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete