Site icon T4Tutorials.com

Object-oriented Factorial of a number in PHP

Write object-oriented Program code in PHP to find the factorial of a number.

<?php
class Factorial {
  private $number;

  // constructor to set the number
  public function __construct($number) {
    $this->number = $number;
  }

  // calculating the factorial
  public function calculate() {
    $t4tutorials = 1;
    for ($i = 1; $i <= $this->number; $i++) {
      $t4tutorials *= $i;
    }
    return $t4tutorials;
  }
}

// create an instance of the Factorial class and pass in the number
$t4tutorials = new Factorial(5);

// call the calculate method to get the factorial
$result = $t4tutorials->calculate();

echo $result; // outputs 120

?>
Exit mobile version