Foundations
Functions
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
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";
$side ← 5
6$side→ 5 = 5; //@side=3, 87$area = square($side5);function square($value)
1<?php2function square($value5) {3 return $value5 * $value;4}$area ← 25
6$side = 5; //@side=3, 87$area→ 25 = square($side5);89echo "side=" . $side5 . "\n";10echo "area=" . $area25 . "\n";outputside=5 area=25
$side ← 3
6$side→ 3 = 3;7$area = square($side3);function square($value)
1<?php2function square($value3) {3 return $value3 * $value;4}$area ← 9
6$side = 3;7$area→ 9 = square($side3);89echo "side=" . $side3 . "\n";10echo "area=" . $area9 . "\n";outputside=3 area=9
$side ← 8
6$side→ 8 = 8;7$area = square($side8);function square($value)
1<?php2function square($value8) {3 return $value8 * $value;4}$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
$sidestarts at5.square($side)sends5into the function.- The function returns
5 * 5. $areabecomes25.- The program prints
side=5andarea=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.