News Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

LeaseWebLabs.com:
How to use the "yield" keyword in PHP 5.5 and up
May 23, 2014 @ 12:09:47

In a recent post to the LeaseWebLabs blog Maurits van der Schee looks at the use of the "yield" keyword in PHP 5.5 to work with generators. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values but it yields values one at a time.

The concept of generators is not new. The "yield" keyword exists in other programming languages as well. As far as I know C#, Ruby, Python, and JavaScript have this keyword. The first usage that comes to mind for me is when I want to read a big text file line-by-line (for instance a log file). Instead of reading the whole text file into RAM you can use an iterator and still have a simple program flow containing a "foreach" loop that iterates over all the lines.

He includes a few code examples showing a class that can read in data from a file in chunks and output the lines as they're extracted (versus using something like file). He also talks about a small performance comparison in working with the file pointer, fread over fgets. He even makes a simple benchmark script to compare the overall time and memory consumption of the fetching of different byte "chunks" from the file.

0 comments voice your opinion now!
yield generator file read fread fgets memory time benchmark

Link: http://www.leaseweblabs.com/2014/05/how-to-use-yield-keyword-php

blog comments powered by Disqus

Similar Posts

MSBWare.com: Alternating Row Colors

Derick Rethans\' Blog: Speaking at PHP Quebec 2006 (and a Reminder)

WebTutor.pl: HipHop for PHP: Benchmark - Revenge of PHP

Blue Parabola Blog: Lies, Damn Lies, and Statistics - Zend's Drupal Benchmarks

Windows Skills Blog: Using SQLite as a database backend for a lightweight server


Community Events

Don't see your event here?
Let us know!


extension framework library conference introduction opinion community php7 voicesoftheelephpant version symfony2 api series performance application laravel interview example podcast release

All content copyright, 2015 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework