Last active
August 29, 2015 14:15
-
-
Save mariano/8143b3e5896a818f267e to your computer and use it in GitHub Desktop.
Is this the only way to extend a method that yields? Yielding each element provided by the parent?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Obviously this is not real code. Otherwise one could | |
* just simply override $multiplier. It is meant to ask | |
* if the only way to extend the logic of a generator | |
* is re-yielding the yielded elements. | |
**/ | |
class Yielder | |
{ | |
protected $multiplier = 1; | |
public function run() | |
{ | |
foreach (range(1, 10) as $number) { | |
yield ($number * $this->multiplier); | |
} | |
} | |
} | |
class Child extends Yielder | |
{ | |
public function run() | |
{ | |
$this->multiplier = 2; | |
foreach (parent::run() as $number) { | |
yield $number; | |
} | |
} | |
} | |
foreach ((new Child())->run() as $number) { | |
var_dump($number); | |
} | |
/** | |
OUTPUTS: | |
$ php yielder.php | |
int(2) | |
int(4) | |
int(6) | |
int(8) | |
int(10) | |
int(12) | |
int(14) | |
int(16) | |
int(18) | |
int(20) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment