PHP Variables

Declare and use variables in PHP. Master naming rules, scope, references, and the difference between variables and constants - the building blocks of every program.

Beginner 8 min read 10 examples

Declaring a Variable

In PHP, a variable starts with a dollar sign $ followed by its name. You don't declare a type - just assign:

PHP declare.php
<?php
$name   = "Ruban";        // string
$age    = 30;             // integer
$price  = 19.99;          // float
$active = true;           // boolean
$tags   = ["php", "web"]; // array

echo $name;               // Ruban
echo $age + 5;            // 35

The assignment operator is =. To check equality use == or (preferred) ===.

Naming Rules

  • Must start with $ followed by a letter or underscore
  • Can contain letters, numbers, and underscores after the first character
  • Cannot start with a number: $1user is invalid
  • Are case-sensitive: $name and $Name are different
PHP
<?php
// Valid
$name       = "ok";
$user_name  = "ok";
$_count     = "ok";
$age2       = "ok";

// Invalid - parse error
// $2user    = "bad";   // starts with number
// $user-name = "bad";  // hyphen not allowed
// $user name = "bad";  // space not allowed
Naming convention

Use snake_case for variable names: $user_email, $total_amount. This matches PHP's own functions (str_replace, array_map). Use camelCase for method names instead.

PHP is Dynamically Typed

The same variable can hold different types over its lifetime:

PHP
<?php
$x = 42;            echo gettype($x);  // integer
$x = "hello";       echo gettype($x);  // string
$x = [1, 2, 3];     echo gettype($x);  // array
$x = new stdClass();echo gettype($x);  // object

While flexible, this can cause bugs. Modern PHP encourages explicit types on function signatures.

Variable Scope

Variables live within a specific scope - the region of code where they're accessible:

Local scope (inside functions)

PHP
<?php
$site = "RubanLearn";

function show() {
    echo $site;     // ERROR - undefined variable inside function
}
show();

Pass variables as parameters (recommended)

PHP
<?php
$site = "RubanLearn";

function show(string $name) {
    echo $name;
}
show($site);        // RubanLearn

The global keyword (avoid)

PHP
<?php
$site = "RubanLearn";

function show() {
    global $site;   // import global into local scope
    echo $site;
}
show();             // RubanLearn

Static variables (preserve state)

PHP
<?php
function counter() {
    static $count = 0;     // initialized only once
    $count++;
    return $count;
}
echo counter();   // 1
echo counter();   // 2
echo counter();   // 3
Avoid globals

Global variables make code hard to test and reason about. Prefer dependency injection: pass values as parameters or inject objects through constructors.

Reference vs Value

By default PHP passes variables by value - the function gets a copy. To share the same variable, use a reference with &:

PHP
<?php
// By value (default)
function increment($n) { $n++; }
$x = 5;
increment($x);
echo $x;            // 5 (unchanged)

// By reference
function incrementRef(&$n) { $n++; }
$x = 5;
incrementRef($x);
echo $x;            // 6 (changed!)

// Reference assignment
$a = 10;
$b = &$a;
$b = 99;
echo $a;            // 99 - $a and $b point to the same value
Objects are different

Object variables (created with new) are passed as object handles by default. Mutating the object inside a function affects the caller's object. This often surprises beginners coming from value semantics.

Variable Variables

PHP lets you use the value of one variable as the name of another. Use sparingly - it makes code hard to follow:

PHP
<?php
$key   = "color";
$$key  = "blue";    // creates $color = "blue"

echo $color;        // blue
echo ${$key};       // blue (preferred syntax)

// Real-world: dynamic property access (use arrays instead)
$data = ["color" => "blue", "size" => "M"];
echo $data["color"];   // cleaner

Constants

Constants hold values that never change. Define them with const or define():

PHP
<?php
// const - compile-time, must be at top-level (or in class)
const API_KEY = "abc123";
const PI       = 3.14159;

// define() - runtime, can be inside conditionals
if (!defined("APP_ENV")) {
    define("APP_ENV", "production");
}

// Use - NO dollar sign
echo API_KEY;
echo APP_ENV;

// Check existence
if (defined("API_KEY")) { /* ... */ }
Featureconstdefine()
WhereTop-level, classAnywhere
ConditionalNoYes
SpeedFaster (compiled)Slower
Case-sensitiveYesYes (since PHP 8)

Predefined Variables (Superglobals)

PHP gives you several built-in arrays that are accessible from any scope without global:

SuperglobalContains
$_GETURL query string parameters
$_POSTForm POST data
$_SERVERRequest headers, paths, server info
$_SESSIONUser session data
$_COOKIEHTTP cookies sent by the browser
$_FILESUploaded files
$_ENVEnvironment variables
$GLOBALSAll variables in global scope
PHP
<?php
// Read a URL param: /page.php?id=5
$id = $_GET["id"] ?? null;

// Read form data
$email = $_POST["email"] ?? "";

// Server info
echo $_SERVER["REQUEST_METHOD"];    // GET / POST
echo $_SERVER["REMOTE_ADDR"];       // visitor IP
Never trust superglobals directly

Data in $_GET, $_POST, and $_COOKIE comes from the user. Always validate and sanitize before using it in HTML (use htmlspecialchars()) or SQL (use prepared statements).

Next Steps

Variables hold data - next learn what kinds of data they can hold:

Frequently Asked Questions

The $ sigil makes variables visually distinct from function names, constants, and language keywords. It also lets you embed variables directly inside double-quoted strings: "Hello $name".

Yes. $age, $Age, and $AGE are three separate variables. This catches many beginners. Function names and class names, by contrast, are not case-sensitive.

No - PHP is dynamically typed. You can assign any type to any variable. However, you can add type declarations on function parameters, return types, and class properties for safety: function add(int $a, int $b): int.

= assigns a value. == compares values with type juggling ("5" == 5 is true). === compares values and types ("5" === 5 is false). Always prefer === to avoid surprises.

PHP has strict scope. Functions don't automatically see outside variables. Either pass them as parameters (preferred) or declare them as global $var; inside the function (avoid).