PHP Variables
Variable Basics
Section titled “Variable Basics”Variable Declaration
Section titled “Variable Declaration”PHP variables are created the moment you assign a value to them. Unlike some languages, you don’t need to explicitly declare variables before use.
- They start with the $symbol followed by the variable name.
// Variables are created the moment you assign a value$message = "Hello, World!";$count = 42;$price = 19.99;$isActive = true;$items = array("apple", "banana", "orange");- The dollar sign distinguishes variables from other programming elements like function names or keywords. Without it, PHP wouldn’t know whether you’re referring to stored data or trying to use a command.
- The dollar sign serves as a signal flag that says “container ahead!”
- It’s PHP’s way of immediately telling you “this is a variable” when you read the code.
Variable Naming Rules
Section titled “Variable Naming Rules”- Must start with $followed by a letter or underscore
- Can contain letters, numbers, and underscores
- Case-sensitive ($nameand$Nameare different)
- Cannot start with a number
// Valid variable names$userName = "john";$user_name = "john";$_userName = "john";$userName123 = "john";
// Invalid variable names// $123user = "john";     // Cannot start with number// $user-name = "john";   // Hyphens not allowed// $user name = "john";   // Spaces not allowedThe Human-Readable Rules for Better Code
Section titled “The Human-Readable Rules for Better Code”<?php// Good variable names tell a story$customer_email = "alice@email.com";    // Anyone reading this knows exactly what data this contains$monthly_salary = 5000;                 // Clear time period and purpose$is_logged_in = true;                   // Boolean variables often start with "is_" to show true/false nature
// Poor variable names create confusion$x = "alice@email.com";                 // What does 'x' mean? You'll forget in a week$data = 5000;                           // What kind of data? Too vague to be helpful$flag = true;                           // What is this flag for? Unclear purpose?>The Technical Rules PHP Enforces
Section titled “The Technical Rules PHP Enforces”<?php// These work perfectly - PHP accepts them$user_name = "John";           // Letters and underscores - excellent choice$totalPrice = 99.99;           // CamelCase - also perfectly valid$_temporary = "temp data";      // Starting underscore - allowed for special cases$item2 = "second item";        // Numbers after letters - completely fine
// These will break your program - PHP rejects them$2users = "invalid";           // Cannot start with a number - think about it: how would PHP distinguish this from the number 2 followed by "users"?$user-name = "broken";         // Hyphens confused with minus signs - PHP thinks you're trying to subtract$for = "problem";              // "for" is a reserved word - PHP needs it for loops?>Variable Scope
Section titled “Variable Scope”A. Global Scope
Section titled “A. Global Scope”Variables declared outside functions have global scope:
$globalVar = "I'm global";
function testGlobal() {    global $globalVar;  // Access global variable    echo $globalVar;}
// Alternative using $GLOBALSfunction testGlobals() {    echo $GLOBALS['globalVar'];}B. Local Scope
Section titled “B. Local Scope”Variables declared inside functions are local:
function testLocal() {    $localVar = "I'm local";    echo $localVar;  // Works fine}
testLocal();// echo $localVar;  // Error: Undefined variableC. Static Variables
Section titled “C. Static Variables”Retain their value between function calls:
function counter() {    static $count = 0;    $count++;    echo "Count: $count\n";}
counter(); // Count: 1counter(); // Count: 2counter(); // Count: 3D. Superglobal Variables
Section titled “D. Superglobal Variables”Built-in variables available everywhere:
// $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, $_ENV, $_FILESecho $_SERVER['HTTP_HOST'];    // Current domainecho $_GET['param'];           // URL parameterecho $_POST['field'];          // Form field
// $GLOBALS contains all global variables$GLOBALS['customVar'] = "Available everywhere";Variable References
Section titled “Variable References”A. Reference Assignment
Section titled “A. Reference Assignment”$original = "Hello";$reference = &$original;  // $reference points to $original
$reference = "World";echo $original;  // Outputs: "World"
// Both variables point to the same memory locationunset($reference);echo $original;  // Still outputs: "World"B. Passing by Reference
Section titled “B. Passing by Reference”function modifyValue(&$value) {    $value = $value * 2;}
$number = 10;modifyValue($number);echo $number;  // Outputs: 20C. References with Arrays
Section titled “C. References with Arrays”$array = [1, 2, 3, 4, 5];
// Modify array elements by referenceforeach ($array as &$value) {    $value *= 2;}unset($value); // Always unset reference after foreach
print_r($array); // [2, 4, 6, 8, 10]Variable Best Practices
Section titled “Variable Best Practices”Naming Conventions
Section titled “Naming Conventions”// Use descriptive names$userName = "john_doe";           // Good$u = "john_doe";                  // Bad
// Use camelCase or snake_case consistently$firstName = "John";              // camelCase$first_name = "John";             // snake_case
// Boolean variables should be descriptive$isActive = true;                 // Good$active = true;                   // Less clear
// Constants in UPPER_CASEconst MAX_RETRY_ATTEMPTS = 3;Type Safety
Section titled “Type Safety”// Use strict types (PHP 7+)declare(strict_types=1);
function addNumbers(int $a, int $b): int {    return $a + $b;}
// Input validationfunction processAge($age) {    if (!is_numeric($age) || $age < 0 || $age > 150) {        throw new InvalidArgumentException('Invalid age provided');    }    return (int)$age;}Variable Initialization
Section titled “Variable Initialization”// Initialize variables before use$total = 0;$items = [];$user = null;
// Use null coalescing operator (PHP 7+)$username = $_GET['user'] ?? 'guest';$config = $userConfig ?? $defaultConfig ?? [];
// Null coalescing assignment (PHP 7.4+)$cache ??= expensive_operation();Memory Management
Section titled “Memory Management”// Unset large variables when done$largeArray = range(1, 1000000);// ... process arrayunset($largeArray);
// Use references for large data structuresfunction processLargeArray(array &$data) {    // Process without copying the array    foreach ($data as &$item) {        $item = strtoupper($item);    }}