我在程序中使用stdObject方法,本质上是想知道是否有可能返回引用:
//standard way using classes
$txt='hello';
class test {
function & gettxt(){
global $txt;
return $txt;
}
function disp(){
global $txt;
echo $txt;
}
}
$o=new test();
$txt_ref=& $o->gettxt();
$txt_ref='world';
$o->disp();//displays world
建议使用以下语法:
//codefragment1:
//from php.net
class stdObject {
public function __call($method,$arguments){
if(isset($this->{$method})&&(is_callable($this->{$method}))
return call_user_func_array($this->{$method},$arguments);
else
throw new Exception("Fatal error: Call to undefined method, $method");
}
}
$txt='hello';
$o=new stdObject();
$o->getvalue=function & () use (&$txt) { return $txt;};
$o->disp=function() use (&$txt) { echo $txt;};
$txt_ref=& $o->getvalue();//error only variables should be assigned by reference
$txt_ref='world';
$o->disp();//hoping for 'world'
答案 0 :(得分:0)
class stdobject {
function & __call($method,$args){
if(substr($method,-1)==='_')
$r=& ($this->{$method})();
else
$r=($this->{$method})();
return $r;
}
}
$txt='hello';
$o=new stdobject();
$o->getvalue_=function & () use (&$txt) { return $txt;};
$o->disp=function () use (&$txt) { echo $txt; };
$txt_ref=& $o->getvalue_();
$txt_ref='world';
$o->disp(); // world
我确定了这个解决方案
php5要求返回引用的函数编写为
$fn=$o->getvalue_;
$r=& $fn();