我在我的程序中使用了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'
发布于 2018-09-14 20:58:42
您提出的建议是一个坏主意,因为它打破了面向对象编程中的封装规则,因为您试图获得对对象内部属性的直接引用,而这在OO中通常是被禁止的。
实现它的正确方法是添加一个setter方法:
class test {
public setValue($val)
{
$this->value = $val;
}
}
然而,如果你坚持要打破OO编程的规则,你可以通过公开对象的内部属性来做到这一点:
class test {
public $value;
}
$o=new test();
$o->value = 'world';
https://stackoverflow.com/questions/52330005
复制相似问题