1. php
  2. /basics
  3. /variables

Introduction to PHP variables

Definition

In PHP, variables are used to store and manipulate data. A variable is a container for a value, and it is defined by a name that begins with a dollar sign ($).

Variable Fundamentals

Variables are the foundation of dynamic programming, acting as named storage locations in memory. When you create a variable, PHP allocates memory to store the value and associates it with the name you provide. This abstraction allows you to work with data without worrying about memory addresses or low-level details.

Key Characteristics of PHP Variables:

  • Dynamic Typing: Variables can hold any data type and change types during execution
  • Reference Counting: PHP tracks how many references point to each value for memory management
  • Automatic Memory Management: PHP handles allocation and deallocation automatically
  • Scope-Based Lifetime: Variables exist within their defined scope and are destroyed when out of scope

The basic syntax for declaring a variable in PHP is:

$variable_name = value;

Naming Rules and Conventions:

  • Must start with a dollar sign ($)
  • After the $, must begin with a letter or underscore
  • Can contain letters, numbers, and underscores
  • Cannot contain spaces or special characters
  • Case-sensitive (e.g., $name and $Name are different)

For example:

$name = "John Doe";
$age = 30;
$is_student = false;

Variable Declaration Insights:

In the examples above, three variables are declared: $name, $age, and $is_student. The variable $name is assigned the string value "John Doe", the variable $age is assigned the integer value 30 and the variable $is_student is assigned the boolean value false.

Each assignment demonstrates PHP's type inference:

  • $name: PHP recognizes the quotes and creates a string variable
  • $age: PHP sees a numeric literal and creates an integer
  • $is_student: PHP recognizes the boolean keyword and creates a boolean

This automatic type assignment simplifies code but requires careful attention to avoid type-related bugs.

Dynamic Typing in PHP

PHP is a loosely typed language, which means that the type of a variable does not need to be specified when it is declared. PHP automatically assigns the correct data type based on the value that is assigned to the variable.

Benefits of Dynamic Typing:

  • Flexibility: Variables can adapt to different data types as needed
  • Rapid Development: Less boilerplate code for type declarations
  • Easy Prototyping: Quick experimentation without type constraints
  • Natural Type Conversion: PHP handles many conversions automatically

Potential Pitfalls:

  • Type Confusion: Variables might not contain the expected type
  • Runtime Errors: Type-related issues appear during execution, not compile time
  • Performance Impact: Type checking happens at runtime
  • Debugging Challenges: Type-related bugs can be subtle

It's also possible to change the value of a variable by re-assigning a new value to it

$name = "Jane Smith"; // the value of $name is now "Jane Smith"

Variable Reassignment Behavior:

When you reassign a variable:

  • The old value is marked for garbage collection if no other references exist
  • The variable now points to the new value in memory
  • The type can change completely: $x = 5; $x = "hello"; is valid
  • Previous type information is lost unless explicitly stored

Variable Naming and Case Sensitivity

It's important to note that variable names in PHP are case-sensitive, which means that $name and $Name are two different variables.

Case Sensitivity Implications:

  • Prevents naming conflicts but can cause confusion
  • Common source of bugs in large codebases
  • Convention helps: use consistent casing throughout your project
  • Modern IDEs can help catch case mismatches

Best Naming Practices:

  • Use descriptive names: $userEmail instead of $e
  • Follow a consistent convention: camelCase or snake_case
  • Avoid ambiguous abbreviations
  • Consider the variable's scope when naming

Superglobal Variables

Also, PHP has some predefined variables called superglobals, they are automatically available in all scopes and can be accessed from anywhere in the script, examples of superglobals are $_GET, $_POST, $_SERVER and $_SESSION

Understanding Superglobals:

Superglobals are built-in associative arrays that provide access to important data:

  • $_GET: Data from URL parameters (query strings)
  • $_POST: Data from HTTP POST requests (forms)
  • $_SERVER: Server and environment information
  • $_SESSION: Session variables for user state
  • $_COOKIE: HTTP cookie values
  • $_FILES: Information about uploaded files
  • $GLOBALS: References to all global scope variables
  • $_REQUEST: Combined $_GET, $_POST, and $_COOKIE (use with caution)
  • $_ENV: Environment variables

These variables are:

  • Automatically populated by PHP
  • Available in any scope without the global keyword
  • Essential for web application development
  • Should be validated and sanitized when containing user input

Examples

Working with Variables in Practice

<?php

$name = "John Doe";
$age = 30;
$is_student = false;

echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Is a student: " . $is_student . "<br>";

Understanding the Output:

When PHP outputs boolean values:

  • true displays as "1"
  • false displays as empty string (nothing)
  • Use var_export() for debugging to see actual boolean values
  • Consider converting booleans to strings for display: $is_student ? 'Yes' : 'No'

The concatenation operator (.) combines strings with other values, automatically converting non-strings as needed.

$age = 35; // re-assign new value to the variable

echo "Updated age: " . $age . "<br>";

$name = "Jane Smith"; // re-assign new value to the variable

echo "Updated name: " . $name . "<br>";

?>

Variable Lifecycle Demonstration:

In this example, three variables are declared: $name, $age, and $is_student. Then the variables are printed out to the screen with the echo statement, the output will be:

Name: John Doe
Age: 30
Is a student: false

Then the values of the variables are re-assigned and printed out again, the output will be:

Updated age: 35
Updated name: Jane Smith

Key Observations:

  • Variables maintain their values until explicitly changed
  • No declaration needed before reassignment
  • Type can change during reassignment (though not shown here)
  • Previous values are lost unless stored elsewhere

As you can see, the values of the variables can be changed and printed out multiple times.

Also, in the example above, it's possible to see that PHP automatically assigns the correct data type based on the value that is assigned to the variable, $name is a string, $age is an integer, and $is_student is a boolean.

Variable Scope

Understanding variable scope is crucial for writing maintainable PHP code:

Global Scope: Variables declared outside any function or class

  • Accessible throughout the script
  • Can be accessed in functions using global keyword
  • Stored in $GLOBALS superglobal

Local Scope: Variables declared inside functions

  • Only accessible within that function
  • Destroyed when function execution completes
  • Parameters are local to the function

Static Variables: Local variables that persist between function calls

  • Initialized only once
  • Retain value between calls
  • Useful for counters or caching
$globalVar = "I'm global";

function demonstrateScope() {
    $localVar = "I'm local";
    global $globalVar;
    static $staticVar = 0;
    
    $staticVar++;
    echo "Static variable: $staticVar<br>";
}

Best Practices

  1. To make it easy to understand which variable is being used and for what purpose, it is important to use clear and descriptive variable names.

    Good names act as documentation. $userEmail immediately tells you what the variable contains, while $e requires checking the code context. This becomes crucial in team environments and when maintaining code months later.

  2. Use a consistent naming convention throughout your code, such as camelCase or snake_case.

    Consistency reduces cognitive load. Pick one style and stick to it:

    • camelCase: $userName, $accountBalance
    • snake_case: $user_name, $account_balance
    • Match your team's or framework's conventions
  3. Always initialize variables before using them, even if you know the value will be assigned later.

    Uninitialized variables can cause "undefined variable" notices and unpredictable behavior. Initialize with appropriate default values:

    $count = 0;
    $name = '';
    $items = [];
    $user = null;
    
  4. Avoid using short variable names, as they can make code more difficult to read and understand.

    Exception: Loop counters ($i, $j) and well-established conventions ($e for exceptions in catch blocks). Otherwise, be descriptive: use $index instead of $i when the context isn't obvious.

  5. Avoid using abbreviations when naming variables, as they can make code more difficult to read and understand.

    $usrMgr saves a few characters but hurts readability. Use $userManager instead. Your IDE's autocomplete makes long names easy to type.

  6. Avoid using keywords, such as "function" or "class" as variable names.

    PHP reserves certain words. Using them causes parse errors. Also avoid names that might become reserved in future PHP versions. Check PHP's reserved words list when in doubt.

  7. Use underscores to separate words in long variable names, to make them more readable.

    This applies when using snake_case. For camelCase, capitalize each word's first letter. Choose based on your project's convention.

  8. Be aware of the scope of variables and the impact that changes to them can have on the rest of the script.

    Understand where variables are accessible and how modifications affect other parts of your code. Use function parameters and return values instead of relying on global state.

  9. As much as possible, try to avoid using global variables and instead pass variables as function arguments or use object-oriented programming techniques to access shared data.

    Global variables create hidden dependencies and make testing difficult. They can be modified from anywhere, making bugs hard to track. Use dependency injection, class properties, or function parameters instead.

  10. Avoid creating unnecessary variables, as they can make code more difficult to understand and maintain.

    Each variable adds mental overhead. However, don't sacrifice clarity for brevity. Intermediate variables can improve readability:

    // Hard to read:
    $result = processData(fetchUser(validateInput($_POST['id'])));
    
    // Clearer:
    $userId = validateInput($_POST['id']);
    $user = fetchUser($userId);
    $result = processData($user);
    

Type Juggling and Strict Types

PHP 7+ introduced strict typing options:

declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

This helps catch type-related bugs early while maintaining PHP's flexibility where needed. Consider using strict types in new projects for better type safety.