Last Updated: February 25, 2016
·
586
· 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#php
#recursive
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside