Lets suppose i have a class & i have to set instance variable from inside the callback.
class A{
protected $user;
public __construct(){
/* Some function here which accept callback */
StoreData(['name'=>'Stackoverflow'],function($response){
//how to assign value to $user here???
});
}
}
What about something like this?
class A{
protected $user;
public function __construct(){
$this->user = 'hehexd';
}
public function getFunction(){
$temp = $this->user; // or a reference
$rval = function($response) use ($temp){
echo $temp;
};
return $rval;
}
}
$a = new A();
$func = $a->getFunction();
$func('response');
exit;
You can assign the entire object to a variable and inject it into the use()
thereby modifying the object (presumably this is what you mean?) :
<?php
class bug
{
protected $user;
public function test()
{
$thisObj = $this;
goo('test',function() use ($thisObj) {
$thisObj->user = 'foooooooo';
});
echo $this->user;
}
}
function goo($val,$callback)
{
$callback();
}
$bug = new bug();
$bug->test();
You will get:
foooooooo
$message = 'hello';
// No "use"
$example = function () {
var_dump($message);
};
$example();
// Inherit $message
$example = function () use ($message) {
var_dump($message);
};
$example();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.