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

Scotch.io:
Understanding PHP Generators
Oct 28, 2016 @ 16:20:44

The Scotch.io blog has posted a tutorial that wants to introduce you to and help you understand a feature recently added to the PHP language: generators. In this new article author Samuel Oloruntoba walks you through some of the basics and offers advice on when to use this helpful feature.

When it comes to driving, speed is not everything. But on the web, speed makes all the difference. The faster your application, the better the user experience. Well, this article is on PHP Generators, so why are we talking about speed? As you are soon about to find out, generators make a huge difference on speed and memory management.

He starts off by explaining what generators are and gives a simple code example showing how they can replace a standard loop (without some of the memory overhead). He uses a for and foreach loop to show a memory overflow caused by it trying to reach the highest integer allowed in the config. To help solve this, he makes use of generators, a much more memory efficient method that only returns the latest value requested and doesn't keep the remainder in memory. He then answers the question of why you might need to even use generators, how to return keys and send values into the generator. He also offers a word of advice on using them - mostly to not overuse them as it's still possible to have issues (like the memory one above).

tagged: generator example introduction tutorial memory yield

Link: https://scotch.io/tutorials/understanding-php-generators


Trending Topics: