Last Updated: February 25, 2016
·
376
· florenceokosun

Recursiveness PHP

This is a simple code snippet for calculating factorial recursively using PHP:

class Factorial {
   protected $number;

   public function __construct($number){
       $this->number = $number;
   }

   public function getFactorial()
   {
       if ($this->number < 2){
         return 1;
       }

    else {
        return $this->number * ($this->getFactorial($this->number -=1));
    }
}

}

$factorial = new Factorial(4);
echo $factorial->getfactorial();

You may wrap your logic inside a try catch block to ensure the number entered is indeed an integer.

1 Response
Add your response

Well thank you too! I'm glad you benefited from my Protip.

over 1 year ago ·