Home  >  Article  >  Backend Development  >  What is the closure in php?

What is the closure in php?

angryTom
angryTomOriginal
2019-08-23 15:27:573412browse

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

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

Result: hello;

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

Result: hello;

$message='world';
  echo $example();

Result: world;

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

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!

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
Previous article:PHP annotation methodNext article:PHP annotation method