Home > Backend Development > PHP Tutorial > What is the closure in php?

What is the closure in php?

angryTom
Release: 2023-04-07 09:58:01
Original
3489 people have browsed it

What is the closure in php?

Closure function: Temporarily create a function without a name, often used as a callback function. In layman's terms: child functions can use local variables in the parent function. This behavior is called closure.

Recommended tutorial: PHP video tutorial

1. Anonymous function assignment

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

2. Closures can inherit variables from the parent scope. 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

Result: hello;

$example=function() use (&$message){
    var_dump($message);
  }
 
Copy after login

Result: hello;

$message='world';
  echo $example();
Copy after login

Result: world;

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

Result: hello world;

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

Related labels:
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