- FEATURES
- Autoload
- Class Reflection
- Magic Methods
- Exceptions
- Late Static Binding
- SPL
- PHPUNIT
- PHAR
- COMPOSER
- Carbon
- Guzzle
- Faker
- Math
- Requests
- DESIGN PATTERNS
- Singleton Pattern
- Observer Pattern
- Strategy Pattern
- Dependency Injection
- Middleware
- Service Layer
- Registry
- SYMFONY
- Routes
- Annotations
- Flex
- Controllers
- Doctrine
- Templating
- VERSIONS
- Php7.4
- Php8.0
- SECURITY
- Filter Input
- Remote Code Injection
- Sql Injection
- Session Fixation
- File Uploads
- Cross Site Scripting
- Spoofed Forms
- CSRF
- Session Hijacking
- MODERN PHP
- Composer
- Autoloader
- Package
- Releases
-
Generators
- Dependency Injection
- Middleware
- CUSTOM FRAMEWORK
- App
- Http Foundation
- Front Controller
- Routing
- Render Controller
- Resolver
- SoC
- FRAMEWORKS
- Slim
- Symfony V5
- Laravel V8
- Laminas V3
- Codeigniter V4
PHP PAGES - LEVEL 2
Yield values
A generator function looks like a normal function, except of returning a value. It yields as many values as it needs to.
function myGenerator()
{
for ($i=1; $i<=3; $i++) {
yield $i;
}
}
Generator class is implementing Iterator interface.
You have to loop over to get values.
function myGenerator()
{
for ($i=1; $i<=3; $i++) {
yield $i;
}
}
foreach (myGenerator() as $v) {
echo $v . PHP_EOL;
}
// Outputs: 1 2 3
Yield doesn't stop the execution of the function and returning,
Yield provides a value and pause the execution of the function.
Examples
This is an example without generator (bad).
code
// bad example
function makeRange($length)
{
$data = array();
$i = 0;
while( $i++ < $length) $data[] = $i;
echo round(memory_get_usage() / 1024 / 1024, 2) . ' MB'. "<br>";
return $data;
}
foreach(makeRange(1000000) as $v) {} // 32.38 MB
foreach(makeRange(3000000) as $v) {} // Allowed memory exhausted
This is how generators save memory (good).
// yield example
function makeRange($length)
{
$i = 0;
while( $i++ < $length) yield $i;
echo round(memory_get_usage() / 1024 / 1024, 2) . ' MB'. "<br>";
}
foreach(makeRange(1000000) as $v) {} // 0.37 MB
foreach(makeRange(3000000) as $v) {} // 0.37 MB
Big files example,
function makeFile() {
if ($fd = fopen("generators.txt", "w+")) {
$i = 0;
while($i++ < 10000000) { // 128 MB allowed in php
fwrite($fd, $i . " GGG <br>");
}
fclose($fd);
}
}
//makeFile(); // 152 MB generators.txt
function getRows() {
if ($fd = fopen("generators.txt", "rb")) {
while (!feof($fd)) {
yield fgets($fd, 4096);
}
}
}
function getRowsArray() {
$data = array();
if ($fd = fopen("generators.txt", "rb")) {
while (!feof($fd)) {
$data[] = fgets($fd, 4096);
}
}
return $data;
}
// yield
foreach(getRows() as $v) {} echo "it works with yield";
// array
foreach(getRowsArray() as $v) {}
// Allowed memory size of 134217728 bytes exhausted
Questions and answers:
Clink on Option to Answer
1. Which statement is used when using generators?
- a) yield $a;
- b) return $a;