// lab.php
Annotated, runnable examples of PHP 8 features from the books. Select a topic and explore.
Topics
Using temporary intermediate variables creates unnecessary memory allocations — each new variable holds a reference until garbage collected. Reassigning the original variable keeps memory usage flat and communicates intent: this is the same value being refined, not a new one.
<?php
// ── Snippet 1: Intermediate variables ────────────────────────────────────────
// Each assignment allocates a new zval (PHP internal value container).
// $tempVar and $tempVar1 linger until garbage collection.
$originalVariable = " hello world ";
$tempVar = strtoupper($originalVariable); // new allocation
$tempVar1 = trim($tempVar); // another new allocation
$originalVariable = $tempVar1; // copy reference back
echo $originalVariable . "\n"; // HELLO WORLD
// $tempVar and $tempVar1 still occupy memory here until scope ends
// or GC runs — wasteful for large strings or tight loops.
// ── Snippet 2: Reassigning the original variable ──────────────────────────────
// PHP uses copy-on-write (CoW). Reassigning the same variable reuses
// the zval slot once the old reference count drops to zero.
// No extra variables = no extra GC overhead.
$originalVariable = " hello world ";
$originalVariable = strtoupper($originalVariable); // refcount drops, reuse
$originalVariable = trim($originalVariable); // same slot again
echo $originalVariable . "\n"; // HELLO WORLD
// ── Why it matters at scale ───────────────────────────────────────────────────
// In a tight loop over a large dataset the difference is measurable.
$data = array_fill(0, 100000, " some value ");
// Slower: creates two extra variables per iteration
$start = microtime(true);
foreach ($data as $item) {
$step1 = strtoupper($item);
$step2 = trim($step1);
$result = $step2;
}
echo "Temp vars: " . round((microtime(true) - $start) * 1000, 2) . "ms\n";
// Faster: single variable, no extra allocations
$start = microtime(true);
foreach ($data as $item) {
$item = strtoupper($item);
$item = trim($item);
}
echo "Reassigned: " . round((microtime(true) - $start) * 1000, 2) . "ms\n";Want to go deeper? Read the books →