Variable scope
Local scope
Variables created inside a function are local: they exist only while the function runs and stay invisible outside it. An outer variable with the same name is a different variable, so the two never overwrite each other by accident.
$name = "Ada";
function show(): void {
$name = "Grace";
echo $name;
}
show();
echo $name;
The global keyword
The global keyword imports an outer variable into the function, so reads and writes touch the shared copy. It works, but it hides the data flow: prefer parameters for input and return for output, and reserve global for small scripts and legacy code.
$total = 0;
function addBonus(int $points): void {
global $total;
$total = $total + $points;
}
addBonus(5);
echo $total;
Static variables
A static variable inside a function keeps its value between calls. It initializes once and then remembers, which suits counters, caches of expensive results, and one-time setup flags.
function counter(): int {
static $n = 0;
$n++;
return $n;
}
echo counter();
echo counter();
Pass by value and reference
Scalar arguments pass by value: the function works with a copy, and the caller variable stays unchanged. An & before a parameter passes by reference instead, so assignments inside the function modify the caller variable directly. Use references sparingly and document them, because hidden writes surprise readers.
function bump(int &$n): void {
$n++;
}
$x = 1;
bump($x);
echo $x;
Next: include and require
Автор статьи: Arthur Isaev