fizzbuzz decorator - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of fizzbuzz decorator.php

  1.  
  2. <?php
  3.  
  4. abstract class Rule
  5. {
  6.     abstract protected function apply(int $number, bool $match);
  7.     
  8.     public function eval(int $number)
  9.     {
  10.         $this->apply($number, false);
  11.     }
  12. }
  13.  
  14. class Bottom extends Rule
  15. {
  16.     public function apply(int $number, bool $matched)
  17.     {
  18.         if(! $matched) { 
  19.             printf('%d', $number);
  20.         }
  21.         echo PHP_EOL;
  22.     }
  23. }
  24.  
  25. class Decorator extends Rule
  26. {
  27.     private $name;
  28.     private $number;
  29.     private $nested_rule;
  30.  
  31.     public function __construct(int $number, string $name, Rule $rule)
  32.     {
  33.         $this->number = $number;
  34.         $this->name = $name;
  35.         $this->nested_rule = $rule;
  36.     }
  37.  
  38.     public function apply(int $number, bool $matched)
  39.     {
  40.         if ($number % $this->number == 0) {
  41.             echo $this->name;
  42.             $this->nested_rule->apply($number, True);
  43.         } else {
  44.             $this->nested_rule->apply($number, $matched);
  45.         }
  46.     }
  47. }
  48.  
  49. $FizzBuzzBazzRule = 
  50.    new Decorator(3, 'Fizz', 
  51.      new Decorator(5, 'Buzz', 
  52.        new Decorator(7, 'Bazz', 
  53.          new Bottom())));
  54.  
  55. $FizzBuzzBazzRule->eval(3);
  56. $FizzBuzzBazzRule->eval(5);
  57. $FizzBuzzBazzRule->eval(7);
  58. $FizzBuzzBazzRule->eval(15);
  59. $FizzBuzzBazzRule->eval(21);
  60. $FizzBuzzBazzRule->eval(35);
  61. $FizzBuzzBazzRule->eval(105);
  62. $FizzBuzzBazzRule->eval(19);
  63. ?>
  64.  
  65.  
File Description
  • fizzbuzz decorator
  • PHP Code
  • 05 Jun-2020
  • 1.29 Kb
You can Share it: