Difference between next () and nextElement () in RecursiveIteratorIterator

What is the difference between RecursiveIteratorIterator::next() and RecursiveIteratorIterator::nextElement() ?

The documentation is a little less useful:

+4
source share
2 answers

From a look at the source of PHP, it seems that nextElement is a callback function that can be called "when the next element is available."

 288 if (object->nextElement && (object->mode == RIT_SELF_FIRST || object->mode == RIT_CHILD_FIRST)) { 289 zend_call_method_with_0_params(&zthis, object->ce, &object->nextElement, "nextelement", NULL); 290 } 

Source

The default nextElement function in the iterator class does nothing so far to look at spl_iterators.c: 801 .

Now it looks like no-op, since there is no way to register your own callback for this function in the PHP source, it currently does nothing. From looking at the code, if registered, that callback is called when the iterator moves forward to the next element before acting on the element (for example, user line code in a foreach loop).

See @RamboCoder answer for an explanation of how to use it.

+3
source

A sample template of the template method appears in some spl classes, this is one of the cases. You are expected to extend the RecursiveIteratorIterator to provide an implementation for additional hooks, and then the superclass (RecursiveIteratorIterator) will call them at the appropriate times.

 class A extends RecursiveIteratorIterator { function nextElement() { echo 'hi'; } } $r = new A(new RecursiveArrayIterator([1,2])); iterator_to_array($r);//hihi 

You can think of the next element () as an event handler, except that you need to extend the class to provide a handler implementation.

Some of the other methods you can hook in are beginChildren () beginIteration () callHasChildren (), etc.

+3
source

All Articles