PHP Variables

A variable is a named container that holds a value. The value stored inside a variable can change during the execution of a script — hence the word "variable." Variables are fundamental to every PHP program because they allow data to be stored, retrieved, and manipulated.

Declaring Variables in PHP

In PHP, a variable always starts with the dollar sign ($) followed by the variable name. PHP does not require declaring a data type before assigning a value — the type is determined automatically based on what is stored.

<?php
  $name = "Alice";
  $age = 30;
  $price = 9.99;
  $isLoggedIn = true;

  echo $name;      // Outputs: Alice
  echo $age;       // Outputs: 30
  echo $price;     // Outputs: 9.99
?>

Each variable is assigned a value using the equals sign (=), which is the assignment operator. The variable immediately holds that value for the rest of the script — or until it is reassigned.

Variable Naming Rules

PHP enforces specific rules for naming variables:

  • A variable name must start with a dollar sign $.
  • The name after $ must begin with a letter or underscore — never a number.
  • The name can contain letters, numbers, and underscores.
  • Variable names are case-sensitive: $score and $Score are different variables.
  • No spaces or special characters (like -, @, or !) are allowed in names.
<?php
  $firstName = "John";    // Valid
  $first_name = "John";   // Valid
  $_tempValue = 42;       // Valid
  $value1 = 100;          // Valid

  // $1value = 5;         // Invalid - starts with a number
  // $my-name = "Ali";    // Invalid - contains a hyphen
?>

Naming Conventions

PHP developers commonly use two naming styles:

  • camelCase — first word lowercase, following words capitalized: $userName, $totalPrice
  • snake_case — all lowercase with underscores: $user_name, $total_price

Either style works. The important thing is to pick one and stay consistent throughout a project.

Reassigning Variables

A variable can be given a new value at any point in the script. The old value is simply replaced.

<?php
  $city = "London";
  echo $city;     // Outputs: London

  $city = "Paris";
  echo $city;     // Outputs: Paris
?>

Variable Scope

Scope refers to where in a script a variable can be accessed. PHP has three main scope levels.

Global Scope

A variable declared outside of any function is a global variable. It is accessible anywhere in the script — except inside functions, unless explicitly brought in.

<?php
  $message = "Hello from global scope";

  function showMessage() {
    // $message is NOT accessible here directly
    echo $message;  // This produces a warning - $message is undefined inside the function
  }

  showMessage();
?>

Accessing Global Variables Inside Functions

To use a global variable inside a function, declare it with the global keyword:

<?php
  $siteName = "LearnPHP";

  function displaySite() {
    global $siteName;
    echo "Welcome to " . $siteName;
  }

  displaySite();  // Outputs: Welcome to LearnPHP
?>

Local Scope

A variable declared inside a function exists only within that function. It is destroyed when the function finishes executing.

<?php
  function greet() {
    $greeting = "Good morning!";
    echo $greeting;  // Works fine inside the function
  }

  greet();
  // echo $greeting;  // This would cause an error - $greeting doesn't exist here
?>

Static Variables

Normally, a local variable is wiped clean each time a function runs. Declaring a variable as static preserves its value between function calls.

<?php
  function countVisits() {
    static $count = 0;
    $count++;
    echo "Visit number: " . $count . "<br>";
  }

  countVisits();  // Outputs: Visit number: 1
  countVisits();  // Outputs: Visit number: 2
  countVisits();  // Outputs: Visit number: 3
?>

Without static, the count would reset to 0 every time the function is called.

Variable Variables

PHP allows the value of one variable to become the name of another variable. This is called a variable variable and uses double dollar signs ($$).

<?php
  $animal = "cat";
  $$animal = "fluffy";

  echo $cat;    // Outputs: fluffy
  echo $$animal; // Also outputs: fluffy
?>

Variable variables are rarely needed in everyday PHP but are useful in certain dynamic scenarios like building form handlers.

Key Points

  • Variables in PHP start with $ followed by the variable name.
  • PHP automatically detects the data type based on the assigned value.
  • Variable names are case-sensitive and cannot start with a number.
  • Global variables are not accessible inside functions unless the global keyword is used.
  • Local variables exist only within the function where they are declared.
  • Static variables retain their value between function calls.

Leave a Comment

Your email address will not be published. Required fields are marked *