代码之家  ›  专栏  ›  技术社区  ›  Ties

在php中创建对象时如何通过引用传递变量

  •  2
  • Ties  · 技术社区  · 14 年前

    所以我想扩展这个例子 RecursiveIterator from the SPL 使用每个函数,我可以轻松地遍历对象/数组

    class it extends RecursiveArrayIterator {
        public function each( $function, $args=array() ){
            $args = (sizeof($args)>0) ? array_merge(array($this),(array)$args) : array($this);
            iterator_apply( $this, $function, $args );
            return $this;
        }
    }
    //Running it:
    $it = new it( &$array );
    $it->each( function( $it ){
        $it->offsetSet( $it->key(),  $it->current() + 1 );
        return true;
    });
    

    已弃用:在中已弃用按引用传递调用时间。。。

    allow_call_time_pass_reference On ? 我在PHP5.3中使用wamp。

    1 : http://www.php.net/manual/en/class.recursivearrayiterator.phpin ...

    2 回复  |  直到 14 年前
        1
  •  1
  •   Artefacto    14 年前

    您必须更改构造函数以引用方式获取变量;但这在这里是不可能的,因为即使您更改了类的构造函数,您仍然必须调用父构造函数,而父构造函数不以引用方式获取。

    解决方案必须涉及更改 ArrayIterator::__construct 通过引用接收数组。

    原则上,您可以使用 call_user_func_array ,但是这不适用于内部函数(在本例中, 数组计算器::\u构造 );参见 bug #52940 .

    确实如此 工作:

    public function __construct(&$array) {
        call_user_func_array('parent::__construct', array(&$array));
    }
    
        2
  •  1
  •   Dennis Haarbrink    14 年前

    RecursiveArrayIterator 继承自 ArrayIterator 使用以下构造函数原型: ArrayIterator::__construct($array, $flags = 0)