Skip to content

Instantly share code, notes, and snippets.

@meadsteve
Last active August 29, 2015 13:56
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 meadsteve/8938621 to your computer and use it in GitHub Desktop.
Save meadsteve/8938621 to your computer and use it in GitHub Desktop.
Exception Looper - because it helps me relax
<?php
class ControlFlowception extends \Exception {}
class Breakception extends ControlFlowception {}
class Countception extends ControlFlowception
{
protected $count;
protected $max;
protected $loopWork;
public function __construct($initialValue, $max, callable $loopWork)
{
$this->count = $initialValue;
$this->max = $max;
$this->loopWork = $loopWork;
$this->next();
}
protected function next() {
try {
if ($this->count <= $this->max) {
throw new self($this->count, $this->max - 1, $this->loopWork);
}
}
catch(Breakception $stop) {
throw $stop;
}
catch(Countception $next) {
$doWork = $this->loopWork;
$doWork($this->max);
}
}
}
// Usage:
try {
throw new Countception(0, 5, function($i) {
echo $i;
if ($i == 3) {
throw new Breakception();
}
});
}
catch (ControlFlowception $e) {
echo PHP_EOL . "Execution complete";
}
catch (\Exception $e) {
echo PHP_EOL . "Unhandled bad exception: " . $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment