首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHP stdObject -动态分配的函数返回引用

PHP stdObject -动态分配的函数返回引用
EN

Stack Overflow用户
提问于 2018-09-14 18:24:31
回答 1查看 128关注 0票数 0

我在我的程序中使用了stdObject方法,并且本质上想知道是否可以返回一个引用:

代码语言:javascript
复制
//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

php.net : anonymous functions

建议使用以下语法:

代码语言:javascript
复制
//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'
EN

回答 1

Stack Overflow用户

发布于 2018-09-14 20:58:42

您提出的建议是一个坏主意,因为它打破了面向对象编程中的封装规则,因为您试图获得对对象内部属性的直接引用,而这在OO中通常是被禁止的。

实现它的正确方法是添加一个setter方法:

代码语言:javascript
复制
class test {
    public setValue($val)
    {
       $this->value = $val;
    }
}

然而,如果你坚持要打破OO编程的规则,你可以通过公开对象的内部属性来做到这一点:

代码语言:javascript
复制
class test {
    public $value;
}

$o=new test();
$o->value = 'world';
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52330005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档