Chapter 6

Functions and Program Structure

A function is a name attached to a piece of behavior. Give it explicit inputs, one clear result, and a scope of its own.

Chapter 6, Functions and Program Structure

What you will learn

  • Define and call functions with parameters and return values.
  • Explain parameters versus arguments and return versus echo.
  • Use local scope and avoid unnecessary globals.
  • Add scalar type declarations and return types where they clarify contracts.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

6.1 Why Functions Matter

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

function celsiusToFahrenheit(float $celsius): float
{
    return ($celsius * 9 / 5) + 32;
}

echo celsiusToFahrenheit(0) . PHP_EOL;
echo celsiusToFahrenheit(100) . PHP_EOL;

6.2 Scope and Side Effects

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

function makeTotal(): int
{
    $total = 10;

    return $total;
}

echo makeTotal() . PHP_EOL;
var_dump(isset($total));

6.3 Type Declarations and Defaults

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

function invoiceLine(string $item, int $quantity = 1, float $unitPrice = 0.0): string
{
    return $item . " x" . $quantity . " = " . number_format($quantity * $unitPrice, 2);
}

echo invoiceLine("Notebook") . PHP_EOL;
echo invoiceLine("Notebook", unitPrice: 4.50, quantity: 3) . PHP_EOL;

Type this one as well, and predict it before you run it.

PHP
<?php

// This file has no declare(strict_types=1) line, on purpose.

function isPassing(int $score): bool
{
    return $score >= 60;
}

var_dump(isPassing("72"));

TPRM Lab 6.1: Area as a Returning Function

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

function rectangleArea(float $width, float $height): float
{
    return $width * $height;
}

$area = rectangleArea(7, 3);
echo "Area: " . $area . PHP_EOL;

TPRM Lab 6.2: A Default Parameter

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

function greet(string $name, string $greeting = "Hello"): string
{
    return $greeting . ", " . $name . "!";
}

echo greet("Maya") . PHP_EOL;
echo greet("Noah", "Welcome") . PHP_EOL;

Back to PHP the TPRM Way