Analysis of PHP Closure Instance

  • 2021-07-18 07:18:20
  • OfStack

This article analyzes the PHP program design in the concept of closure machine usage, sharing for your reference. The specific analysis is as follows:

Generally speaking, closures are anonymous functions of PHP, but unlike functions, closures can use the values of variables in the scope of which the function is declared through use.

The specific form is as follows:


$a = function($arg1, $arg2) use ($variable) { 
//  Declare function closures to variables $a,  Parameter is $arg1, $arg2 , This closure requires the use of the $variable Variable 
}

Specific usage examples are as follows:


<?php
$result = 0;
 
$one = function()
{ var_dump($result); };
 
$two = function() use ($result)
{ var_dump($result); }; //  It can be considered that  $two This variable   It records the declaration of the function and use Values of variables used 
 
$three = function() use (&$result)
{ var_dump($result); };
 
$result++;
 
$one();  // outputs NULL: $result is not in scope
$two();  // outputs int(0): $result was copied
$three();  // outputs int(1)
?>

I hope this article for everyone PHP programming learning has a certain reference and help.


Related articles: