views:

53

answers:

2

So I want to extend for example this RecursiveIterator from the SPL with the function each so i can easily walk over the object/array

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;
});

Which results in:

Deprecated: Call-time pass-by-reference has been deprecated in ...

The problem is i can't, or shouldn't, use the reference when creating the object because its depricated. But when iterating over the array/object i want to be able to make changes to it, how can i achieve this without changing the allow_call_time_pass_reference to On? I'm using wamp with php 5.3.

Have a nice day

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

+1  A: 

There isn't an obvious way to achieve this. The RecursiveArrayIterator inherits from ArrayIterator with the following constructor prototype: ArrayIterator::__construct($array, $flags = 0)

This means the argument is not passed by reference. And if I recall correctly, you are not allowed to change to signature to accept params by-ref.

Dennis Haarbrink
+1  A: 

You would have to change the constructor to take the variable by reference; but that's not possible here, because even if you changed the constructor for your class, you'd still have to call the parent constructor, which doesn't take by reference.

The solution would have to involve changing the signature of ArrayIterator::__construct to receive the array by reference.

In principle, you would be able to override the call-time pass-by-reference limitation with call_user_func_array, however that doesn't work with internal functions (in this case, ArrayIterator::__construct); see bug #52940.

This does not work:

public function __construct(&$array) {
    call_user_func_array('parent::__construct', array(&$array));
}
Artefacto