bhylu.com

Advertisements

PHP Variable Scope

A function is easier to test when the values it needs are visible in its parameters. Hidden global state makes a result depend on more than the call appears to say.

How it works

PHP function-local scope does not automatically import variables from the surrounding file. global and $GLOBALS can access global bindings, but ordinary application logic usually benefits from explicit arguments or injected collaborators. A static local persists between calls in one execution; it is not durable storage between independent web requests. Keep request data at the boundary and pass validated values into domain functions.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l scope.php
php scope.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · scope.php

<?php
declare(strict_types=1);

$defaultDays = 7;
function describeLoan(string $item, int $days): string { return "$item for $days days"; }
echo describeLoan("Spade", $defaultDays), "\n";
function callsInThisExecution(): int { static $calls = 0; return ++$calls; }
echo callsInThisExecution(), ",", callsInThisExecution(), "\n";

Expected result

Spade for 7 days
1,2

The first function receives the dependency instead of reaching into file scope. The counter intentionally has execution-local retained state, so its second call sees the first call’s increment. Running the script again starts a new ordinary CLI execution; this is not a persistent site-wide visitor counter.

Check the official PHP manual for detailed version and API contracts.