PHP code example of ehough / generators

1. Go to this page and download the library: Download ehough/generators library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ehough / generators example snippets


$generator = function ($values) {
    print "Let's get started\n";
    foreach ($values as $key => $value) {
        yield $key => $value;
    }
    print "Nothing more to do\n";
};

$items = array('foo' => 'bar', 'some' => 'thing');

foreach ($generator($items) as $k => $v) {
    print "The generator gave us $k => $v\n";
}

use Hough\Generators\AbstractGenerator

class MyGenerator extends \Hough\Promise\AbstractGenerator
{
    private $keys;
    private $values;

    public function __construct(array $items)
    {
        $this->keys   = array_keys($items);
        $this->values = array_values($items);
    }

    protected function resume($position)
    {
        // first execution
        if ($position === 0) {
            print "Let's get started\n";
        }

        // still inside the for loop
        if ($position < count($this->values)) {

            // return an array of two items: the first is the yielded key, the second is the yielded value
            return array(
                $this->keys[$position],
                $this->values[$position]
            );
        }

        // we must be done with the for loop, so print our last statement and return null to signal we're done
        print "Nothing more to do\n";
        return null;
    }
}

$items = array('foo' => 'bar', 'some' => 'thing');
foreach (new MyGenerator($items) as $k => $v) {
    print "The generator gave us $k => $v\n";
}