Junior — Senior
Configuring the string representation of the Math object
livecode
Task condition
It is required to modify the existing code so that when attempting to output an object of the Math class via echo (without explicitly calling a method), it displays the factorial value of the number passed to the constructor.
class Math
{
public function __construct(private int $value)
{
}
public function factorial(): int
{
if ($this->value < 0) {
throw new Exception("value less 0");
}
$product = 1;
for ($i = 1; $i <= $this->value; $i++) {
$product *= $i;
}
return $product;
}
}
$math = new Math(-5);
try {
echo $math->factorial();
} catch (Exception $e) {
echo $e->getMessage();
}
Your task is to add the necessary mechanism (for example, the magic method __toString) that will return the result of factorial() and thus ensure correct output when using echo $math;.