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
$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:
$1useris invalid - Are case-sensitive:
$nameand$Nameare different
<?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
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
$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
$site = "RubanLearn";
function show() {
echo $site; // ERROR - undefined variable inside function
}
show();
Pass variables as parameters (recommended)
<?php
$site = "RubanLearn";
function show(string $name) {
echo $name;
}
show($site); // RubanLearn
The global keyword (avoid)
<?php
$site = "RubanLearn";
function show() {
global $site; // import global into local scope
echo $site;
}
show(); // RubanLearn
Static variables (preserve state)
<?php
function counter() {
static $count = 0; // initialized only once
$count++;
return $count;
}
echo counter(); // 1
echo counter(); // 2
echo counter(); // 3
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
// 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
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
$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
// 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")) { /* ... */ }
| Feature | const | define() |
|---|---|---|
| Where | Top-level, class | Anywhere |
| Conditional | No | Yes |
| Speed | Faster (compiled) | Slower |
| Case-sensitive | Yes | Yes (since PHP 8) |
Predefined Variables (Superglobals)
PHP gives you several built-in arrays that are accessible from any scope without global:
| Superglobal | Contains |
|---|---|
$_GET | URL query string parameters |
$_POST | Form POST data |
$_SERVER | Request headers, paths, server info |
$_SESSION | User session data |
$_COOKIE | HTTP cookies sent by the browser |
$_FILES | Uploaded files |
$_ENV | Environment variables |
$GLOBALS | All variables in global scope |
<?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
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: