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

时间:2018-09-14 10:24:31

标签: php

我在程序中使用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 : anonymous functions

建议使用以下语法:

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

1 个答案:

答案 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

我确定了这个解决方案

  • php7
  • 它使用一种编程约定,即返回引用的函数应声明其名称以下划线结尾
  • 此示例未提供该函数的参数,但可以使用多种方法合并
  • php5要求返回引用的函数编写为

    $fn=$o->getvalue_;
    $r=& $fn();