How do I make the methods of the Iterator subclass observe array pointer functions?

Standard functions current

key

and next

seem to ignore the methods of the Iterator subclass.

In this example, I simply override the method Iterator::current

to return the modified string. My method seems to have a different state of the parent class. It does not have access to the same pointer and does not run when current()

called on an instance.

<?php

class DecoratingIterator extends ArrayIterator {

    public function current(){
        return '**'.strtoupper( parent::current() ).'**';
    }
}

$test = new DecoratingIterator( ['foo','bar'] );

next($test);

echo $test->current(),"\n"; 
// prints "**FOO**"

echo current($test),"\n";   
// prints "bar"

      

I'm sure this is the expected behavior, but is there a way to make my subclass methods work when a PHP function is called on it?

+3


source to share


1 answer


This answer requires APD functionality to be installed .

The reason for this is current

, key

and next

are not part of ArrayIterator

, and even if they were, you would still be calling ArrayIterator::current()

which launches the original method in ArrayIterator

. What you need to do is overwrite the function current

and let it call your new function using override_function

. Something like this should do it ( NB: I haven't tested this).



rename_function('current', 'original_current');
override_function('current', '$obj', 'return override_current($obj);');
function override_current($obj)
{
    if ($obj instanceof DecoratingIterator)
    {
        return $obj->current();
    }
    else
    {
        return original_current($obj);
    }
}

      

+1


source







All Articles