Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
The scope of a variable is the context within which it is defined. PHP has a function scope and a global scope. Any variable defined outside a function is limited to the global scope. When a file is included, the code it contains inherits the variable scope of the line on which the include occurs.
Variables Scope: Global and Function
$globalVar = "I'm global"; function testScope() { $localVar = "I'm local"; echo $localVar; //echo $globalVar; // Warning: Undefined variable $globalVar } testScope(); // I'm local echo $globalVar; // I'm global //echo $localVar; // Warning: Undefined variable $localVar
Arrow Functions Scope
Arrow functions, automatically inherit variables from the parent scope. Unlike normal anonymous functions (function() use ($x)), arrow functions don’t need the use keyword for capturing variables.
$number = 10; $multiply = fn($x) => $x * $number; // $number is inherited automatically echo $multiply(5); // 50
The global Keyword
If you want to use a global variable inside a function, you need to declare it with the global keyword.
$counter = 0; function increaseCounter() { global $counter; $counter++; } increaseCounter(); increaseCounter(); echo $counter; // 2
Static Variables
A static variable inside a function retains its value between multiple calls. Unlike normal local variables, it is not destroyed when the function ends.
function increment() { static $count = 0; // initialized only once $count++; return $count; } echo increment(); // 1 echo increment(); // 2 echo increment(); // 3
Variable Variables
PHP allows you to use the value of a variable as the name of another variable. This is called variable variables.
$varName = "greeting"; $greeting = "Hello, world!"; echo $$varName; // Hello, world!
Source: Orkhan Alishov's notes