Variables in PHP are containers for storing data values (strings, integers, arrays, objects). All PHP variables begin with a dollar sign $ followed by the variable name.
_.A-z, 0-9, and _).$age and $AGE are two separate variables).$validVar = "Allowed";
$_user_id = 101;
//$2ndRank = "Invalid!"; // Syntax Error!
PHP has three distinct variable scopes: local, global, and static.
flowchart TD
A["PHP Variable Scopes"] --> B["Local Scope"]
A --> C["Global Scope"]
A --> D["Static Scope"]
B --> E["Declared inside function; inaccessible outside"]
C --> F["Declared outside function; requires 'global' keyword or $GLOBALS inside"]
D --> G["Declared inside function; retains state across calls"]
<?php
declare(strict_types=1);
// Global Scope Variable
$appName = "Kodersolution Engine";
function displayCounter(): void
{
// Accessing Global Variable via $GLOBALS superglobal
echo "App Name: " . $GLOBALS['appName'] . "
";
// Static Variable: retains value across multiple function calls
static $visitCount = 0;
$visitCount++;
// Local Scope Variable
$localMessage = "Function Call #" . $visitCount;
echo $localMessage . "
";
}
displayCounter(); // Output: Call #1
displayCounter(); // Output: Call #2
displayCounter(); // Output: Call #3
// Attempting to access $localMessage here causes Undefined Variable Error!
$userEmail) or snake_case ($user_email) throughout project repositories.static for Cached State within Functions: Ideal for memoization or counter logic that persists across function invocations within the request execution.Create a function trackDownloads() containing a static $count = 0; variable that increments and prints the download count every time the function is called!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.