Functions name reusable work and return values to the caller.

function call A function call runs the named function and can use the returned value in another expression.

Functions

side
functions.php
Replay: real traced execution (multi-file project)
<?php
function square($value) {
    return $value * $value;
}

$side = 5;
$area = square($side);

echo "side=" . $side . "\n";
echo "area=" . $area . "\n";
<?php
function square($value) {
    return $value * $value;
}

$side = 3;
$area = square($side);

echo "side=" . $side . "\n";
echo "area=" . $area . "\n";
<?php
function square($value) {
    return $value * $value;
}

$side = 8;
$area = square($side);

echo "side=" . $side . "\n";
echo "area=" . $area . "\n";
  1. $side ← 5

    6$side→ 5 = 5; //@side=3, 87$area = square($side5);
  2. function square($value)

    1<?php2function square($value5) {3    return $value5 * $value;4}
  3. $area ← 25

    6$side = 5; //@side=3, 87$area→ 25 = square($side5);89echo "side=" . $side5 . "\n";10echo "area=" . $area25 . "\n";
    outputside=5
    area=25
  1. $side ← 3

    6$side→ 3 = 3;7$area = square($side3);
  2. function square($value)

    1<?php2function square($value3) {3    return $value3 * $value;4}
  3. $area ← 9

    6$side = 3;7$area→ 9 = square($side3);89echo "side=" . $side3 . "\n";10echo "area=" . $area9 . "\n";
    outputside=3
    area=9
  1. $side ← 8

    6$side→ 8 = 8;7$area = square($side8);
  2. function square($value)

    1<?php2function square($value8) {3    return $value8 * $value;4}
  3. $area ← 64

    6$side = 8;7$area→ 64 = square($side8);89echo "side=" . $side8 . "\n";10echo "area=" . $area64 . "\n";
    outputside=8
    area=64

Follow the Function Call

  1. $side starts at 5.
  2. square($side) sends 5 into the function.
  3. The function returns 5 * 5.
  4. $area becomes 25.
  5. The program prints side=5 and area=25. | side | square result | | --- | --- | | 3 | 9 | | 5 | 25 | | 8 | 64 |

Exercise: functions.php

Reproduce area=25 for side 5, then try side 3 and 8 and predict each area before running it.