Skip to content

Instantly share code, notes, and snippets.

@do-aki
Created August 15, 2014 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save do-aki/f14174a31ca00e9c808b to your computer and use it in GitHub Desktop.
Save do-aki/f14174a31ca00e9c808b to your computer and use it in GitHub Desktop.
同じメソッドで foreach も each(function) もできるようにする例
<?php
class R {
private $begin;
private $end;
public function __construct($begin, $end) {
$this->begin = $begin;
$this->end = $end;
}
public function each(callable $closure = null) {
return self::eachlize(function () {
for ($i=$this->begin;$i <= $this->end; ++$i) {
yield $i;
}
}, $closure);
}
public static function eachlize(callable $each, callable $callback = null) {
if ($callback === null) {
return $each();
}
foreach ($each() as $v) {
$callback($v);
}
}
}
$r = new R(1,3);
foreach ($r->each() as $v) {
echo $v;
}
echo "\n";
$r->each(function($v) {
echo $v;
});
echo "\n";
$ php eachlize.php
123
123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment