Book Image

The PHP Workshop

By : Jordi Martinez, Alexandru Busuioc, David Carr, Markus Gray, Vijay Joshi, Mark McCollum, Bart McLeod, M A Hossain Tonu
Book Image

The PHP Workshop

By: Jordi Martinez, Alexandru Busuioc, David Carr, Markus Gray, Vijay Joshi, Mark McCollum, Bart McLeod, M A Hossain Tonu

Overview of this book

Do you want to build your own websites, but have never really been confident enough to turn your ideas into real projects? If your web development skills are a bit rusty, or if you've simply never programmed before, The PHP Workshop will show you how to build dynamic websites using PHP with the help of engaging examples and challenging activities. This PHP tutorial starts with an introduction to PHP, getting you set up with a productive development environment. You will write, execute, and troubleshoot your first PHP script using a built-in templating engine and server. Next, you'll learn about variables and data types, and see how conditions and loops help control the flow of a PHP program. Progressing through the chapters, you'll use HTTP methods to turn your PHP scripts into web apps, persist data by connecting to an external database, handle application errors, and improve functionality by using third-party packages. By the end of this Workshop, you'll be well-versed in web application development, and have the knowledge and skills to creatively tackle your own ambitious projects with PHP.
Table of Contents (12 chapters)

4. Functions

Activity 4.1: Creating a Calculator

Solution

  1. Create a new file within the Chapter04 directory with the name activity.php.
  2. Start your script with the opening PHP tag and set the strict type to 1:
    <?php
    declare(strict_types=1);
  3. 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...