首页 > 解决方案 > 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

php.net:匿名函数

建议使用这种语法:

//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'

标签: php

解决方案


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

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

class test {
    public setValue($val)
    {
       $this->value = $val;
    }
}

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

class test {
    public $value;
}

$o=new test();
$o->value = 'world';

推荐阅读