![](/img/trans.png)
[英]PHP access variable from inside an anonymous function callback on the outside?
[英]Access instance variable inside anonymous callback PHP
让我们假设我有一个类,我必须从回调内部设置实例变量。
class A{
protected $user;
public __construct(){
/* Some function here which accept callback */
StoreData(['name'=>'Stackoverflow'],function($response){
//how to assign value to $user here???
});
}
}
这样的事情怎么样?
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;
您可以将整个对象分配给变量并将其注入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();
你会得到:
foooooooo
$message = 'hello';
// No "use"
$example = function () {
var_dump($message);
};
$example();
// Inherit $message
$example = function () use ($message) {
var_dump($message);
};
$example();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.