PHP Tutorial

Variables & Types

Dollar signs, dynamic typing, and primitive types in PHP

Declaring Variables

In PHP, variables always start with a dollar sign ($). You don't need to specify a type when declaring a variable; PHP is a Dynamically Typed language.
php
$name = "Alpha";
$age = 25;
$isReady = true;

Variable Variables (Advanced)

Wait! PHP has a unique feature called "Variable Variables." You can use the value of one variable as the name of another.
php
$foo = "bar";
$$foo = "baz"; // This creates a variable called $bar with value "baz"
echo $bar;     // "baz"

Constant Values

To define a constant that cannot be changed, use the define() function or the const keyword.
php
define("SITE_URL", "https://codex.com");
const VERSION = 1.0;

Data Types

PHP supports several basic data types:
TypeDescription
StringText data ("Hello")
IntegerWhole numbers (42)
FloatDecimal numbers (3.14)
Booleantrue or false
ArrayOrdered map of values
ObjectInstances of classes
NULLRepresents no value

Strict Typing

While PHP is dynamic by default, you can (and should) enable Strict Typing at the top of your file to force types to be checked.
php
declare(strict_types=1);

Summary

TermDescription
$Prefix for all variables
DynamicType is determined at runtime
Globalglobal $var - Accessing variables inside functions
Staticstatic $var - Variable that keeps its value between calls
ConstantImmutable value (define or const)
Best ForWeb requests, form data, session handling
LogicFlexible and easy for beginners to start
SafetyUse declare(strict_types=1) for professional apps
ModernPHP 8 supports union types and property promotion
StandardUse camelCase for variables and PascalCase for classes
IdentityVariables are case-sensitive ($x is not $X)
ScopeLocal by default inside functions