Modern PHP: Difference between revisions

From Rixort Wiki
Jump to navigation Jump to search
No edit summary
Line 9: Line 9:
   yield 3;
   yield 3;
  }
  }
Generators are forward-only iterators, i.e. you can only request the next value, not the previous, next but one etc. They are useful for iterating sequential data sets such as reading a file line by line (in order).


== Useful dependencies ==
== Useful dependencies ==

Revision as of 20:39, 10 April 2018

Generators

Generators are similar to iterators that calculate their values on demand, thus potentially using fewer resources. They can be created using the yield keyword, e.g.:

function my_generator()
{
  yield 1;
  yield 2;
  yield 3;
}

Generators are forward-only iterators, i.e. you can only request the next value, not the previous, next but one etc. They are useful for iterating sequential data sets such as reading a file line by line (in order).

Useful dependencies

Links