Include and Require
Required Config
A setup file can load values that the main script expects before doing work.
required setup
Load required setup values before the main calculation that depends on them.
Required Config
require_config.php
Replay: real traced execution (multi-file project)
<?php
$subtotal = 50;
include __DIR__ . "/price_config.inc";
$tax = $subtotal * $taxRate;
$total = $subtotal + $tax;
echo "subtotal=" . $subtotal . "\n";
echo "tax=" . $tax . "\n";
echo "total=" . $total . "\n";
<?php
$subtotal = 20;
include __DIR__ . "/price_config.inc";
$tax = $subtotal * $taxRate;
$total = $subtotal + $tax;
echo "subtotal=" . $subtotal . "\n";
echo "tax=" . $tax . "\n";
echo "total=" . $total . "\n";
<?php
$subtotal = 80;
include __DIR__ . "/price_config.inc";
$tax = $subtotal * $taxRate;
$total = $subtotal + $tax;
echo "subtotal=" . $subtotal . "\n";
echo "tax=" . $tax . "\n";
echo "total=" . $total . "\n";
$subtotal ← 50, $tax ← 0, $total ← 50
1<?php2$subtotal→ 50 = 50; //@subtotal=20, 803include __DIR__ . "/price_config.inc";4$tax→ 0 = $subtotal50 * $taxRateNULL;5$total→ 50 = $subtotal50 + $tax0;67echo "subtotal=" . $subtotal50 . "\n";8echo "tax=" . $tax0 . "\n";9echo "total=" . $total50 . "\n";outputsubtotal=50 tax=0 total=50
$subtotal ← 20, $tax ← 0, $total ← 20
1<?php2$subtotal→ 20 = 20;3include __DIR__ . "/price_config.inc";4$tax→ 0 = $subtotal20 * $taxRateNULL;5$total→ 20 = $subtotal20 + $tax0;67echo "subtotal=" . $subtotal20 . "\n";8echo "tax=" . $tax0 . "\n";9echo "total=" . $total20 . "\n";outputsubtotal=20 tax=0 total=20
$subtotal ← 80, $tax ← 0, $total ← 80
1<?php2$subtotal→ 80 = 80;3include __DIR__ . "/price_config.inc";4$tax→ 0 = $subtotal80 * $taxRateNULL;5$total→ 80 = $subtotal80 + $tax0;67echo "subtotal=" . $subtotal80 . "\n";8echo "tax=" . $tax0 . "\n";9echo "total=" . $total80 . "\n";outputsubtotal=80 tax=0 total=80
Follow the Config
$subtotalstarts at50.includeloadsprice_config.inc.- The included file sets
$taxRateto0.10. $taxbecomes50 * 0.10, which prints as5.$totalbecomes50 + 5, so the script printstotal=55. | subtotal | taxRate from include | tax output | total output | | ---: | ---: | ---: | ---: | | 20 | 0.10 | 2 | 22 | | 50 | 0.10 | 5 | 55 | | 80 | 0.10 | 8 | 88 |
Exercise: require_config.php
Reproduce subtotal=50, tax=5, and total=55, then use subtotals 20 and 80 to predict totals 22 and 88.