[英]Access instance variable inside anonymous callback PHP
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?) : 您可以将整个对象分配给变量并将其注入use()
从而修改对象(可能这就是您的意思?) :
<?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();
http://php.net/manual/en/functions.anonymous.php http://php.net/manual/en/functions.anonymous.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.