Scope decides where a variable can be used.
Local scope
Variables created inside a function exist only inside it. Also, a function cannot see variables from outside (unlike JavaScript).
$site = 'AgyanAdda';
function show() {
echo $site; // Warning: undefined variable
}
Solutions
- Pass it as a parameter (best):
function show(string $site) global $site;inside the function (avoid — makes code hard to test)- For closures:
function () use ($site) { ... }or arrow functions, which capture outer variables automatically
static variables
Keep their value between calls:
function counter() {
static $count = 0;
return ++$count;
}
Pass by reference
Add & to let a function change the original variable: function addBonus(array &$marks).
Example
Example — Scope, static and reference
PHP
<?php
$siteName = 'AgyanAdda';
function welcome(string $site): string
{
$message = "Welcome to $site"; // local variable
return $message;
}
echo welcome($siteName) . '<br>';
function visitCounter(): int
{
static $visits = 0;
return ++$visits;
}
visitCounter();
visitCounter();
echo 'Visits: ' . visitCounter() . '<br>';
function addGrace(array &$marks, int $grace): void
{
foreach ($marks as &$m) {
$m = min(100, $m + $grace);
}
}
$marks = [30, 55, 98];
addGrace($marks, 5);
echo 'After grace: ' . implode(', ', $marks) . '<br>';
$rate = 18;
$withGst = fn($price) => $price + $price * $rate / 100; // arrow fn sees $rate
echo 'With GST: ' . $withGst(100);
Output: Welcome to AgyanAdda / Visits: 3 / After grace: 35, 60, 100 / With GST: 118