VARIABLES

PHP

VARIABLES

In PHP, a variable assumes the role of a placeholder designated to harbour an array of data types, encompassing numbers, strings, arrays, objects, and various other data entities. Commencing their declaration with the symbolic dollar sign ($), variables are endowed with case sensitivity and possess the capacity to encompass a gamut of characters, inclusive of letters, numbers, and underscores. However, their initiation demands a commencement with either a letter or an underscore.

$name = "John"; // Here, $name is a variable storing a string "John"
$height = 7.9; // Here, $height is a variable storing a number 7.9


Variables in PHP can be reassigned to different values and their content can change throughout the execution of a script. They also have variable scopes, meaning they can be local or global, affecting their accessibility within functions or across the entire script.



RULES FOR CREATING VARIABLES IN PHP:

  • Naming Convention: In accordance with PHP's naming convention, the utilisation of variables mandates a commencement marked by a letter or an underscore, trailing which, the variable may encompass a sequence of alphanumeric characters or underscores. While the dollar sign ($) inherently precedes the variable name during declaration or invocation, it does not constitute part of the variable's nomenclature. For instance, the valid variable name may take the form of $_variableName or $variableName, complying with these standards.

    $_variableName = "value"; // Valid variable name starting with an underscore
    $variableName = "value"; // Valid variable name starting with a letter


  • Case Sensitivity: In the realm of PHP, the handling of variables adheres strictly to case sensitivity. This dictates that variables designated as "$myVar", "$MyVar", and "$myvar" stand as distinct entities, each recognised as a separate variable within the language's construct. Such minute alterations in letter casing delineate unique variables despite their semblance in nomenclature.

    $myVariable = "Hello"; // Declaring a variable with lowercase letters
    echo $myvariable; // Trying to access the variable with a different casing


  • Allowed Characters: Variable naming conventions within PHP allow for a diverse spectrum of characters, encompassing letters, numerical digits, and underscores. Nonetheless, a pivotal criterion necessitates the initial character of a variable name to be either a letter or an underscore. This rule underscores the fundamental structure of valid variable names within the language.

    $myVariable = "Hello"; // Uses letters and camelCase convention
    $_second_variable = 10; // Starts with an underscore and uses underscores
    $var123 = 3.14; // Includes numbers in the variable name
    $my_Va2r = "Example"; // Mixes letters, underscores, and numbers


  • No Spaces: Variable names in PHP adhere strictly to a principle disallowing spaces or the inclusion of special characters, barring underscores, within their nomenclature. This steadfast rule accentuates the necessity for seamless, uninterrupted sequences of characters to delineate variables, ensuring their integrity within the language's syntax.

    // Valid variable names
    $variableName = "Hello, world!"; // Using letters and no spaces
    $_secondVariable = 10; // Starting with an underscore
    $third_variable = 3.14; // Using underscores and numbers

    // Invalid variable names (commented out to prevent errors)
    // $my Variable = "Invalid"; // Contains a space
    // $4thVariable = 4; // Starts with a number
    // $special@char = "Invalid"; // Contains a special character

    // Demonstrating case sensitivity
    $myVar = "First variable"; // Declaring a variable
    $MyVar = "Second variable"; // Another variable with different casing
    $myvar = "Third variable"; // Yet another, distinctly named variable

    echo $myVar; // Outputs: First variable
    echo $MyVar; // Outputs: Second variable
    echo $myvar; // Outputs: Third variable


  • Reserved Keywords: It is prudent to abstain from employing PHP reserved keywords such as "echo", "if", "else", among others, as designations for variables. Steering clear of these reserved terms ensures the avoidance of potential conflicts within the codebase, preserving the clarity and functionality of the PHP script.

    // Incorrect usage: Using a reserved keyword as a variable name
    $if = "Condition"; // "if" is a reserved keyword for conditional statements

    // Correct usage: Avoiding reserved keywords
    $condition = "Condition"; // Using a suitable alternative variable name

    // Usage of a reserved keyword for its intended purpose
    $number = 10;
    if ($number > 5)
    {
        echo "Number is greater than 5";
    }
    else
    {
        echo "Number is 5 or less";
    }


  • Global Scope: In the realm of PHP, variables that find their declaration outside the confines of a function attain a global scope, granting them unrestricted accessibility from any part of the script. Conversely, variables initiated within the boundaries of functions confine themselves to a local scope, solely accessible within the function where they are defined. This demarcation between global and local scopes governs the reach and availability of variables throughout the PHP script's execution.

    // Global scope variable
    $globalVar = "I am global";

    function localScopeExample()
    {
        // Local scope variable
        $localVar = "I am local";

        echo "Inside function: " . $localVar . "<br/>"; // Accessing local variable

        // Accessing global variable from within the function
        global $globalVar;
        echo "Inside function accessing global variable: " . $globalVar . "<br/>";
    }

    echo "Outside function, global variable: " . $globalVar . "<br/>"; // Accessing global variable

    // Trying to access the local variable outside the function (will result in an error)
    // echo "Outside function: " . $localVar . "<br/>";

    localScopeExample(); // Calling the function

    // Attempting to access the local variable outside the function (will result in an error)
    // echo "Outside function: " . $localVar . "<br/>";


  • Dynamic Typing: PHP boasts dynamic typing, eliminating the necessity for explicit declaration of data types during variable instantiation. The type of data encapsulated within a variable is ascertained inherently based on the value attributed to it during assignment, alleviating the need for preemptive type specification within the language's paradigm.

    // Variable $dynamicVar initially holds an integer value
    $dynamicVar = 10;
    echo "Value: " . $dynamicVar . ", Type: " . gettype($dynamicVar) . "<br/>";

    // Reassigning $dynamicVar to a string value
    $dynamicVar = "Hello, PHP!";
    echo "Value: " . $dynamicVar . ", Type: " . gettype($dynamicVar) . "<br/>";

    // Assigning $dynamicVar to a boolean value
    $dynamicVar = true;
    echo "Value: " . $dynamicVar . ", Type: " . gettype($dynamicVar) . "<br/>";

    Output:
    Value: 10, Type: integer
    Value: Hello, PHP!, Type: string
    Value: 1, Type: boolean