Foundations
Variables
Variables store values that later expressions can reuse.
variable
PHP variable names start with `$` and can store strings, numbers, arrays, and other values.
Variables
variables.php
Replay: real traced execution (multi-file project)
<?php
$unitPrice = 12;
$quantity = 3;
$total = $unitPrice * $quantity;
echo "unit=" . $unitPrice . "\n";
echo "total=" . $total . "\n";
<?php
$unitPrice = 8;
$quantity = 3;
$total = $unitPrice * $quantity;
echo "unit=" . $unitPrice . "\n";
echo "total=" . $total . "\n";
<?php
$unitPrice = 20;
$quantity = 3;
$total = $unitPrice * $quantity;
echo "unit=" . $unitPrice . "\n";
echo "total=" . $total . "\n";
$unitPrice ← 12, $quantity ← 3, $total ← 36
1<?php2$unitPrice→ 12 = 12; //@unitPrice=8, 203$quantity→ 3 = 3;4$total→ 36 = $unitPrice12 * $quantity3;56echo "unit=" . $unitPrice12 . "\n";7echo "total=" . $total36 . "\n";outputunit=12 total=36
$unitPrice ← 8, $quantity ← 3, $total ← 24
1<?php2$unitPrice→ 8 = 8;3$quantity→ 3 = 3;4$total→ 24 = $unitPrice8 * $quantity3;56echo "unit=" . $unitPrice8 . "\n";7echo "total=" . $total24 . "\n";outputunit=8 total=24
$unitPrice ← 20, $quantity ← 3, $total ← 60
1<?php2$unitPrice→ 20 = 20;3$quantity→ 3 = 3;4$total→ 60 = $unitPrice20 * $quantity3;56echo "unit=" . $unitPrice20 . "\n";7echo "total=" . $total60 . "\n";outputunit=20 total=60
Follow the Total
$unitPricestarts at12.$quantitystarts at3.$total = $unitPrice * $quantitymultiplies12 * 3.$totalbecomes36.- The program prints
unit=12andtotal=36. | unitPrice | quantity | total | | --- | --- | --- | | 8 | 3 | 24 | | 12 | 3 | 36 | | 20 | 3 | 60 |
Exercise: variables.php
Reproduce unit=12 and total=36, then try unitPrice 8 and 20 and predict each total before running it.