The scope of php anonymous function variables

as shown in the figure, how to access $data? outside anonymous functions more elegantly

Php
Mar.18,2021

inherit variables from parent scope with use

function()use($data){}

add that global and $globals superglobal variables can also read externally defined global variables, learn about


function () use ($data) {}
is more elegant, but it should be noted that the inherited $data value is related to the context of this closure declaration
for example:

[1]
$data = 1;
function() use($data){}//1
[2]
$data = 1;
function() use($data){}
$data = 2;
,$data,1
$data = 1;
$x = function() use ($data){
    var_dump($data);
    exit;
};
$data = 2;
function ttt($a)
{
    $a();
}
ttt($x);
Menu