PHP Variables

Variables in PHP are used to store data. A variable always starts with a $ sign followed by the variable name.

Example:
<?php
    $name = "Samir";
    $age = 25;
    $price = 199.50;

    echo $name;
?>

👉 Explanation:

  • Variables start with $ (e.g., $name).
  • They can store strings, numbers, arrays, objects, etc.
  • Variable names are case-sensitive.

Variable Scope in PHP

Variable scope defines where a variable can be accessed inside a PHP script.

Types of Scope:
  • Local – Inside a function.
  • Global – Outside any function.
  • Static – Retains value between function calls.
Example:
<?php
    $globalVar = "I am global";

    function testScope() {
        $localVar = "I am local";
        echo $localVar;     // Works
        // echo $globalVar; // Error: cannot access global variable directly
    }

    testScope();
?>
Accessing Global Variables:
<?php
    $x = 10;
    $y = 20;

    function addNumbers() {
        global $x, $y;   // Using global keyword
        echo $x + $y;
    }

    addNumbers();
?>
Static Variable Example:
<?php
    function counter() {
        static $count = 0; // Stays in memory
        $count++;
        echo $count . "<br>";
    }

    counter(); // 1
    counter(); // 2
    counter(); // 3
?>

👉 Explanation:

  • Local variables exist only inside the function.
  • Global variables can be accessed using global keyword or $GLOBALS array.
  • Static variables save their value even after the function ends.

PHP Constants

Constants are values that cannot be changed once defined. Unlike variables, constants do not use a $ sign.

Example:
<?php
    define("SITE_NAME", "MyWebsite");
    const VERSION = "1.0";

    echo SITE_NAME;
    echo VERSION;
?>

👉 Explanation:

  • Constants are defined using define() or const.
  • Constants do not use $ and cannot be changed.
  • Constants have global scope by default.
PHP Tutorial