Sobes.tech
Junior — Senior

Integration of factorial calculation into class method

livecode

Task condition

The task requires transforming an existing function that calculates the factorial of a number into a method within a user-defined class. The calculation logic should remain the same, and handling of negative arguments should throw an exception.

class MathOperations {
    public static function factorial(int $num): int {
        if ($num < 0) {
            throw new Exception('num less 0');
        }
        $resultNum = 1;
        for ($i = 1; $i <= $num; $i++) {
            $resultNum *= $i;
        }
        return $resultNum;
    }
}

try {
    echo MathOperations::factorial(-5);
} catch (Exception $e) {
    echo $e->getMessage();
}

Demonstrate its functionality, correctly handling possible errors.