Last active
August 29, 2015 13:56
-
-
Save meadsteve/8938621 to your computer and use it in GitHub Desktop.
Exception Looper - because it helps me relax
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 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