php - PHP stdObject - 动态分配的函数返回一个引用
问题描述
我在我的程序中使用 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'
解决方案
您提出的建议是一个坏主意,因为它违反了面向对象编程中的封装规则,因为您试图获得对对象内部属性的直接引用,而这在 OO 中通常是被禁止的。
实现它的正确方法是添加一个setter方法:
class test {
public setValue($val)
{
$this->value = $val;
}
}
但是,如果您坚持打破 OO 编程规则,您可以通过公开对象的内部属性来做到这一点:
class test {
public $value;
}
$o=new test();
$o->value = 'world';
推荐阅读
- typescript - 内部有任何泛型的数组
- python - 在 Python 中计算文件中单词的实例,仅适用于单个字母
- php - PHP中的套接字并发
- asp.net-mvc-5 - 将 CSS 文件中的背景图像 URL 设置为另一个站点
- reactjs - 无效的 POST 请求
- javascript - 当元素是屏幕之一时如何打开元素上的功能。JS
- c++ - 将运算符提取为非数字字符
- python - Python程序Airnef在下载图像时卡住了
- python-3.x - Python - Networkx:为给定的节点集创建图
- c++ - C++:迭代器 - list.begin() 抛出错误