[英]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.