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.
Written by Picrasma-Excelsa
Related protips
1 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
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#