Created
August 15, 2014 05:49
-
-
Save do-aki/f14174a31ca00e9c808b to your computer and use it in GitHub Desktop.
同じメソッドで foreach も each(function) もできるようにする例
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 | |
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"; |
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 eachlize.php | |
123 | |
123 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment