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.
Result of php executing
Full code of fizzbuzz decorator.php
- <?php
- abstract class Rule
- {
- abstract protected function apply(int $number, bool $match);
- public function eval(int $number)
- {
- $this->apply($number, false);
- }
- }
- class Bottom extends Rule
- {
- public function apply(int $number, bool $matched)
- {
- if(! $matched) {
- printf('%d', $number);
- }
- echo PHP_EOL;
- }
- }
- class Decorator extends Rule
- {
- private $name;
- private $number;
- private $nested_rule;
- public function __construct(int $number, string $name, Rule $rule)
- {
- $this->number = $number;
- $this->name = $name;
- $this->nested_rule = $rule;
- }
- public function apply(int $number, bool $matched)
- {
- if ($number % $this->number == 0) {
- echo $this->name;
- $this->nested_rule->apply($number, True);
- } else {
- $this->nested_rule->apply($number, $matched);
- }
- }
- }
- $FizzBuzzBazzRule =
- new Decorator(3, 'Fizz',
- new Decorator(5, 'Buzz',
- new Decorator(7, 'Bazz',
- new Bottom())));
- $FizzBuzzBazzRule->eval(3);
- $FizzBuzzBazzRule->eval(5);
- $FizzBuzzBazzRule->eval(7);
- $FizzBuzzBazzRule->eval(15);
- $FizzBuzzBazzRule->eval(21);
- $FizzBuzzBazzRule->eval(35);
- $FizzBuzzBazzRule->eval(105);
- $FizzBuzzBazzRule->eval(19);
- ?>