This post is part of a series on Code Challenges.

As I’m sure every developer has, I’ve been tasked with completing the infamous FizzBuzz code challenge at various points in my career. This is a more recent take.

View on Repl.it.


<?php

class FizzBuzz 
{
    /**
     * @var int
     */
    private int $start;
        
    /**
     * @var int
     */
    private int $end;
    
    /**
     * @param int $start
     * @param int $end
     */
    public function __construct(int $start, int $end)
    {
        $this->start = $start;
        $this->end = $end;
    }
    
    /**
     * Run the app
     * @return void
     */
    public function run(): void
    {
        for ($x = $this->start; $x <= $this->end; $x++) {
            $output = '';
            if ($this->isDivisibleByThree($x)) {
                $output .= 'Fizz';
            }
            
            if ($this->isDivisibleByFive($x)) {
                $output .= 'Buzz';
            }
            
            if (empty($output)) {
                $output .= (string)$x;
            }
            $this->print($output);
        }
    }
    
    /**
     * @param int $number
     * @return bool
     */
    private function isDivisibleByFive(int $number): bool
    {
        return $number % 5 === 0;
    }
    
    /**
     * @param int $number
     * @return bool
     */
    private function isDivisibleByThree(int $number): bool
    {
        return $number % 3 === 0;
    }
    
    /**
     * @param string $output
     * @return void
     */
    private function print(string $output): void
    {
        echo "{$output}\r\n";
    }
    
}

(new FizzBuzz(1, 100))->run();

Tagged in: