Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Class FizzBuzz
- *
- * FizzBuzz class implemented in the OOP style. This class will handle all aspects of the FizzBuzz requirements. The user can also
- * create additional divisors and result strings as required. The only divisor implemented by default is 3 for "Fizz".
- *
- * @author Keith Jones
- * @copyright Keith Jones 11/20/2014
- * @version 1.0
- * @since 11/20/2014
- * @package OOPFB
- */
- class FizzBuzz {
- private $count = 0;
- private $outputSent = false;
- private $divisors = array();
- public function FizzBuzz() {
- $this->addDivisor(3, 'Fizz');
- }
- private function setOutputSent ($bool = true) {
- if(is_bool($bool)) {
- $this->outputSent = $bool;
- } else {
- throw new Exception('OutputSent value not boolean');
- }
- }
- private function getOutputSent () {
- return $this->outputSent;
- }
- private function CountIsDivisibleBy($number) {
- return $this->count%$number==0 ? true : false;
- }
- public function addDivisor($divisor, $outputString) {
- if(!is_int($divisor)) {
- throw new Exception('Bad divisor');
- } elseif(!is_string($outputString)) {
- throw new Exception('Bad outputString');
- } else {
- $this->divisors[$divisor] = $outputString;
- return true;
- }
- return false;
- }
- public function Increment($number) {
- if(is_int($number) && $number > 0) {
- $this->count += $number;
- } else {
- throw new Exception('Bad incrementer');
- }
- }
- public function getNumber () {
- return $this->count;
- }
- public function printNumber () {
- $output = '';
- foreach($this->divisors as $divisor => $outputString) {
- if($this->CountIsDivisibleBy($divisor)) {
- echo $outputString;
- $this->setOutputSent();
- }
- }
- if($this->outputSent == false) {
- echo $this->count;
- }
- echo "\n";
- $this->setOutputSent(false);
- }
- }
- $maxNum = 100;
- try {
- $fb = new FizzBuzz();
- $fb->addDivisor(5, 'Buzz');
- } catch (Exception $e) {
- echo 'Instantiation Exception: ' . $e->getMessage() . "\n";
- }
- do {
- try {
- $fb->Increment(1);
- $fb->printNumber();
- } catch (Exception $e) {
- echo 'Exception: ' . $e->getMessage() . "\n";
- }
- } while ($fb->getNumber() < $maxNum);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment