A Simple Example of PHP Closure Definition and Use

  • 2021-09-20 19:36:06
  • OfStack

This article illustrates the definition and use of PHP closures. Share it for your reference, as follows:


<?php
function getClosure($i)
{
  $i = $i.'-'.date('H:i:s');
  return function ($param) use ($i) {
    echo "--- param: $param ---\n";
    echo "--- i: $i ---\n";
  };
}
$c = getClosure(123);
$i = 456;
$c('test');
sleep(3);
$c2 = getClosure(123);
$c2('test');
$c('test');
/*
output:
--- param: test ---
--- i: 123-21:36:52 ---
--- param: test ---
--- i: 123-21:36:55 ---
--- param: test ---
--- i: 123-21:36:52 ---
*/

Let's take another example


$message = 'hello';
$example = function() use ($message){
 var_dump($message);
};
echo $example();
// Output hello
$message = 'world';
// Output hello  Because the value of the variable is inherited when the function is defined, not when the function is defined   When a function is called 
echo $example();
// Reset to hello
$message = 'hello';
// Send a reference here 
$example = function() use(&$message){
 var_dump($message);
};
echo $example();
// Output hello
$message = 'world';
echo $example();
// Output here world
// Closure functions are also used for normal value transfer 
$message = 'hello';
$example = function ($data) use ($message){
 return "{$data},{$message}";
};
echo $example('world');
// Output here world,hello

For more readers interested in PHP related contents, please check the topics of this site: "Summary of php String (string) Usage", "Encyclopedia of PHP Array (Array) Operation Skills", "Tutorial of PHP Data Structure and Algorithm", "Summary of php Programming Algorithm", "Summary of PHP Mathematical Operation Skills" and "Summary of PHP Operation and Operator Usage".

I hope this article is helpful to everyone's PHP programming.


Related articles: