HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Variables

Variables are "containers" for storing information. In PHP, a variable starts with the $ sign, followed by the name of the variable.


1. Declaring Variables

Unlike many other languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

<?php
    $txt = "Hello world!";
    $x = 5;
    $y = 10.5;
?>
PHP is Loosely Typed: You don't have to tell PHP which data type the variable is. PHP automatically associates a data type to the variable, depending on its value.

2. Naming Rules

To write valid PHP, your variable names must follow these specific rules:

  • A variable name must start with the $ sign.
  • A variable name must start with a letter or the underscore character.
  • A variable name cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  • Variable names are case-sensitive ($age and $AGE are different).

3. Variable Scope

Scope refers to the part of the script where a variable can be referenced/used. PHP has three different variable scopes:

A. Global Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.

<?php
    $x = 5; // global scope

    function myTest() {
        // using x inside this function will generate an error
        echo "<p>Variable x inside function is: $x</p>";
    } 
    myTest();

    echo "<p>Variable x outside function is: $x</p>";
?>

B. Local Scope

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.

<?php
    function myTest() {
        $y = 5; // local scope
        echo "<p>Variable y inside function is: $y</p>";
    } 
    myTest();

    // using y outside the function will generate an error
    echo "<p>Variable y outside function is: $y</p>";
?>

The global Keyword

The global keyword is used to access a global variable from within a function. To do this, use the global keyword before the variables (inside the function):

<?php
    $x = 5;
    $y = 10;

    function myTest() {
        global $x, $y;
        $y = $x + $y;
    }

    myTest();
    echo $y; // outputs 15
?>
Static Keyword: Normally, all variables are deleted when a function is completed. However, sometimes we want a local variable NOT to be deleted. To do this, use the static keyword when you first declare the variable.

Key Points to Remember

  • Variables are created the moment they are assigned a value.
  • Always start with a $ followed by a letter or underscore.
  • Use meaningful names (e.g., $userEmail instead of $e).
  • Global variables are declared outside functions; **Local** variables are inside.
  • Use the global keyword to use global variables inside your functions.
  • PHP is loosely typed, so you don't declare types like `int` or `string`.