如何使Iterator子类方法观察数组指针函数?

The standard current key and next functions seem to ignore Iterator subclass methods.

In this example I just override the Iterator::current method to return a modified string. It seems that my method has a different state to the parent class. It doesn't have access to the same pointer, and it doesn't fire when current() is 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(),"
"; 
// prints "**FOO**"

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

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

This answer requires the APD functions to be installed.

The reason for this is current, key and next aren't part of ArrayIterator, and even if they were you would still be calling ArrayIterator::current(), which runs the original method in ArrayIterator. What you need to do is overwrite the function current and instruct it to call your new function using override_function. Something like this should do it (NB: I've not 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);
    }
}