How to recover parameters passed by the use() method, within a function?

Asked

Viewed 41 times

0

I’m studying callbacks and I came across a method that I can’t recover and I find it even simpler to send the variables inside the function that is the operator use, but I don’t know how to get it inside this function my_function().

So far I have understood, the first is the callback of function and the second is the my_function parameter().

function my_function($call, array $foo) { 
    return $foo['ra'];
}


$bar = ['ra' => '853-5'];

$str = my_function(function($data) {
    return $data;
}, $bar);

var_dump($str); //string(5) "853-5"

But so I can use it this way!

$str = my_function(function($data) use ($bar) {
    return $data;
});

And not having to pass the second parameter to the function, but rather the operadoe use. How do I get this data passed by the operator use my_function() ?

Thanks in advance for the reply!

  • 1

    the operator use is to give the freedom of a variable to be used within the callback, and not to pass it on to the function itself.

  • 1

    exactly as @Rafaelacioly said, the use adds variables in the context of callback, this context belongs only to callback and you won’t be able to pick it out of that context

  • Now I understand, thanks and thank you all!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.