4. Functions
Activity 4.1: Creating a Calculator
Solution
- Create a new file within the
Chapter04
directory with the nameactivity.php
. - Start your script with the opening PHP tag and set the strict type to
1
:<?php declare(strict_types=1);
- Now we can start by writing our
factorial
function in the same file:activity.php
13Â function factorial(int $number): float 14Â { 15Â Â Â Â Â $factorial = $number; 16Â Â Â Â Â while ($number > 2) { 17Â Â Â Â Â Â Â Â Â $number--; 18Â Â Â Â Â Â Â Â Â $factorial *= $number; 19Â Â Â Â Â } 20Â Â Â Â Â return $factorial; 21Â }
Let me explain what the function does. First of all, it takes an integer argument; we can be sure that it will always be an integer because we added a type hint and declared that we are using strict types. There are several...