Functions and Scope
Return Values
A function can compute a value and return it to the caller.
return
`return` sends a value back to the expression that called the function.
Return Values
return_values.php
Replay: real traced execution (multi-file project)
<?php
function subtotal(int $price, int $quantity): int {
$total = $price * $quantity;
return $total;
}
$quantity = 3;
$amount = subtotal(7, $quantity);
echo "quantity=" . $quantity . "\n";
echo "amount=" . $amount . "\n";
<?php
function subtotal(int $price, int $quantity): int {
$total = $price * $quantity;
return $total;
}
$quantity = 1;
$amount = subtotal(7, $quantity);
echo "quantity=" . $quantity . "\n";
echo "amount=" . $amount . "\n";
<?php
function subtotal(int $price, int $quantity): int {
$total = $price * $quantity;
return $total;
}
$quantity = 5;
$amount = subtotal(7, $quantity);
echo "quantity=" . $quantity . "\n";
echo "amount=" . $amount . "\n";
$quantity ← 3
7$quantity→ 3 = 3; //@quantity=1, 58$amount = subtotal(7, $quantity3);$total ← 21
1<?php2function subtotal(int $price7, int $quantity3): int {3 $total→ 21 = $price7 * $quantity3;4 return $total21;5}$amount ← 21
7$quantity = 3; //@quantity=1, 58$amount→ 21 = subtotal(7, $quantity3);910echo "quantity=" . $quantity3 . "\n";11echo "amount=" . $amount21 . "\n";outputquantity=3 amount=21
$quantity ← 1
7$quantity→ 1 = 1;8$amount = subtotal(7, $quantity1);$total ← 7
1<?php2function subtotal(int $price7, int $quantity1): int {3 $total→ 7 = $price7 * $quantity1;4 return $total7;5}$amount ← 7
7$quantity = 1;8$amount→ 7 = subtotal(7, $quantity1);910echo "quantity=" . $quantity1 . "\n";11echo "amount=" . $amount7 . "\n";outputquantity=1 amount=7
$quantity ← 5
7$quantity→ 5 = 5;8$amount = subtotal(7, $quantity5);$total ← 35
1<?php2function subtotal(int $price7, int $quantity5): int {3 $total→ 35 = $price7 * $quantity5;4 return $total35;5}$amount ← 35
7$quantity = 5;8$amount→ 35 = subtotal(7, $quantity5);910echo "quantity=" . $quantity5 . "\n";11echo "amount=" . $amount35 . "\n";outputquantity=5 amount=35
Follow the Return
quantitystarts as3.- The call is
subtotal(7, $quantity). - Inside the function, price
7is multiplied by quantity3. - The return value is
21. - The script prints
quantity=3andamount=21. | quantity | calculation | amount | | --- | --- | --- | | 3 |7 * 3| 21 | | 1 |7 * 1| 7 | | 5 |7 * 5| 35 |
Exercise: return_values.php
Reproduce quantity=3 and amount=21, then use the pinned quantity variants 1 and 5 to predict amount=7 and amount=35.