PHP Variables: Naming Rules, Dynamic Typing, Scope & Superglobals

In computer programming, a variable is a named container in computer memory used to hold data values that can be read, manipulated, and updated during program execution. In PHP, variables are uniquely lightweight, dynamic, and flexible. You do not need to pre-allocate variable memory or declare data types ahead of time; PHP automatically handles type casting dynamically based on whatever value you assign.

PHP Variable Naming Rules (Syntax Standards)

When declaring variables in PHP, you must adhere strictly to these fundamental rules:

  • Every variable name MUST begin with a dollar sign ($).
  • The first character after the $ must be either a letter (a-z, A-Z) or an underscore (_).
  • A variable name CANNOT start with a number (e.g., $1stRank is invalid syntax).
  • Variable names may only contain alphanumeric characters and underscores (a-z, A-Z, 0-9, and _). Special symbols, spaces, or hyphens are strictly forbidden.
  • Variable names are case-sensitive ($totalMarks is completely different from $totalmarks).
<?php
    // Valid variable declarations
    $studentName = "Vikram Aditya"; // camelCase (Standard PHP convention)
    $_user_id = 10042;              // Leading underscore
    $total_score_2026 = 98.5;       // Underscore with trailing digits

    // INVALID variable declarations (will trigger Syntax Error)
    // $9rank = 1;                  // Cannot begin with a digit!
    // $user-name = "Rahul";        // Hyphens are not permitted!
    // $user age = 22;              // Spaces are not permitted!
?>

PHP Dynamic Typing (Loosely Typed Language)

Unlike languages like C++ or Java where you must declare int count = 10;, PHP automatically converts variable types based on context:

<?php
    $data = "Veewom";   // $data is currently a String
    echo gettype($data) . "<br>"; // Outputs: string

    $data = 450;        // $data dynamically re-assigned to Integer
    echo gettype($data) . "<br>"; // Outputs: integer

    $data = 79.99;      // $data dynamically re-assigned to Float
    echo gettype($data) . "<br>"; // Outputs: double
?>

Variable Scope: Local, Global & Static

The scope of a variable defines the exact code regions where that variable can be accessed. Understanding scope is essential for BCA semester lab exams:

1. Local Scope

A variable created inside a function has local scope. It is created when the function is invoked and destroyed as soon as the function finishes executing. It cannot be accessed from outside the function:

<?php
    function calculateBonus() {
        $bonus = 5000; // Local scope variable
        echo "Inside function bonus: $" . $bonus . "<br>";
    }

    calculateBonus();
    // echo $bonus; // Error: Undefined variable $bonus (Outside local scope!)
?>

2. Global Scope & The global Keyword

A variable declared outside any function has global scope. By default, PHP protects functions from accidentally modifying global state. If a function needs to access a global variable, it must explicitly declare it with the global keyword:

<?php
    $siteTitle = "Veewom Educational Portal"; // Global variable

    function renderHeader() {
        global $siteTitle; // Imports global variable into local function scope
        echo "Header: " . $siteTitle . "<br>";
    }

    renderHeader();
?>

Alternative: Accessing via $GLOBALS Superglobal

PHP stores all global variables in an associative array named $GLOBALS[index]. You can access or update global variables anywhere without the global keyword:

<?php
    $scoreA = 40;
    $scoreB = 60;

    function addScores() {
        $GLOBALS['totalScore'] = $GLOBALS['scoreA'] + $GLOBALS['scoreB'];
    }

    addScores();
    echo "Total Score from $GLOBALS: " . $totalScore; // Outputs: 100
?>

3. Static Scope

Normally, when a function completes execution, all local variables are deleted from memory. If you want a local variable to persist its value across repeated function calls, prefix it with the static keyword:

<?php
    function visitorCounter() {
        static $visitCount = 0; // Initialized ONLY once on first invocation
        $visitCount++;
        echo "Visitor Number: " . $visitCount . "<br>";
    }

    visitorCounter(); // Outputs: Visitor Number: 1
    visitorCounter(); // Outputs: Visitor Number: 2
    visitorCounter(); // Outputs: Visitor Number: 3
?>

PHP Superglobals Reference Table

PHP provides built-in pre-defined associative arrays called Superglobals. They are globally accessible throughout any script, class, or function without requiring the global keyword:

Superglobal Data Carried & Practical Purpose
$_GET Collects parameters submitted via URL query strings (e.g. ?page=2&id=10).
$_POST Collects data submitted via secure HTTP POST web forms (passwords, user input).
$_REQUEST Combines contents of $_GET, $_POST, and $_COOKIE.
$_SESSION Stores user authentication state across multiple pages on the web server.
$_COOKIE Reads client-side HTTP cookies saved in the user's browser.
$_SERVER Contains server headers, paths, script location, and client IP addresses.
$_FILES Captures uploaded file metadata (name, size, temporary path, error codes).
$GLOBALS References all variables currently defined in global script scope.

BCA / CS University Exam Corner

Semester Exam Question:

Q: Distinguish between variable variables in PHP (e.g., $$var).
A: A variable variable takes the string value of a variable and treats that value as the name of a new variable. For example:
$a = "hello"; $$a = "world"; echo "$a $hello"; // Outputs: hello world.

Interactive Student Practice Session

Exercise 4.1: Create a function named generateInvoiceID() that uses a static variable to produce sequential IDs: INV-1001, INV-1002, INV-1003.

Exercise 4.2: Write a script that reads your operating system user agent and remote IP address using $_SERVER['HTTP_USER_AGENT'] and $_SERVER['REMOTE_ADDR'].

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!