Variables and Constants
Variables and constants are the foundation of data storage in PHP. Variables hold values that can change during your program's execution, while constants store values that remain fixed. Understanding how to properly create, name, and manage these storage mechanisms is essential for writing reliable PHP applications.
PHP's approach to variables offers significant flexibility compared to many programming languages. You don't need to declare variable types upfront, and you can change both the value and type of a variable at any time. This flexibility makes PHP approachable for beginners while still being powerful enough for complex applications.
Understanding Variables
Variables in PHP are named storage locations that hold data your program can use and modify. Think of them as labeled containers where you can store different types of information - text, numbers, true/false values, or more complex data structures.
The key concept here is that variables represent memory locations. When you create a variable, PHP allocates a space in the computer's memory and gives it a name so you can reference it later. This is fundamentally different from just writing literal values like "Hello"
or 42
directly in your code.
Every PHP variable name starts with a dollar sign ($
) followed by the variable name. This syntax serves two important purposes: it immediately identifies variables to both PHP and human readers, and it distinguishes variables from other language elements like function names or keywords.
<?php
// Creating variables - PHP allocates memory and assigns values
$customerName = "Sarah Johnson";
$orderAmount = 149.99;
$isPremiumMember = true;
$itemsInCart = 3;
// Display the stored values
echo "Customer: $customerName<br>";
echo "Order total: $" . number_format($orderAmount, 2) . "<br>";
echo "Premium member: " . ($isPremiumMember ? "Yes" : "No") . "<br>";
echo "Cart items: $itemsInCart<br>";
?>
Unlike languages such as Java or C++ where you must declare a variable's type before using it, PHP uses dynamic typing. This means PHP automatically figures out what type of data you're storing based on the value you assign. You don't need to tell PHP "this will be text" or "this will be a number" - it determines this automatically.
Variables Can Change
The fundamental characteristic that makes something a "variable" is its ability to vary - to change. Unlike mathematical constants, variables in programming are designed to hold different values as your program runs. This mutability is what makes programs dynamic and responsive.
PHP takes this flexibility further than many languages by allowing you to change not just the value stored in a variable, but also the type of data it contains. A variable that starts as text can become a number, then a true/false value, all within the same program execution.
<?php
$userStatus = "Checking login credentials...";
echo "Status: $userStatus<br>";
// Change the value but keep it as text
$userStatus = "Login successful!";
echo "Status: $userStatus<br>";
// Change both value and type - now it's a number
$userStatus = 200; // HTTP status code
echo "Status code: $userStatus<br>";
// Change to boolean
$userStatus = true; // Logged in state
echo "Logged in: " . ($userStatus ? "Yes" : "No") . "<br>";
?>
This flexibility is both powerful and potentially dangerous. It's powerful because you can write code quickly without worrying about rigid type restrictions. It's potentially dangerous because you might accidentally overwrite a variable with the wrong type of data, leading to unexpected behavior.
Variable Naming Rules
Variable naming in PHP follows a combination of technical requirements enforced by the language interpreter and community conventions that make code readable and maintainable. Understanding both aspects helps you write code that not only works but also integrates well with other PHP projects and teams.
Required Naming Rules
PHP's parser enforces these mandatory rules for variable names. Breaking any of these rules will cause a syntax error that prevents your code from running:
- Must start with a dollar sign (
$
) - This tells PHP "what follows is a variable name" - First character after
$
must be a letter (a-z, A-Z) or underscore (_) - Numbers and special characters aren't allowed to start a name - Subsequent characters can be letters, numbers (0-9), or underscores - Once you start with a valid character, you can include numbers
- No spaces or special characters except underscore - Characters like hyphens, periods, or symbols will break parsing
- Case-sensitive - PHP treats uppercase and lowercase letters as completely different
<?php
// Valid variable names - these all work
$userName = "Alice"; // camelCase style
$user_name = "Bob"; // snake_case style
$user2 = "Charlie"; // numbers after letters OK
$_privateData = "hidden"; // underscore prefix OK
echo "All valid: $userName, $user_name, $user2<br>";
echo "Private: $_privateData<br>";
?>
The case sensitivity rule is particularly important because it means $userName
, $username
, and $USERNAME
are three completely different variables. This can lead to frustrating bugs where you think you're using the same variable but you're actually creating new ones due to inconsistent capitalization.
<?php
// These are all different variables due to case sensitivity
$userName = "Alice";
$username = "Bob";
$USERNAME = "Charlie";
echo "userName: $userName<br>";
echo "username: $username<br>";
echo "USERNAME: $USERNAME<br>";
// This creates confusion and bugs
$orderTotal = 100.00;
$ordertotal = 50.00; // Accidentally created a new variable
echo "Which total? $orderTotal or $ordertotal?<br>";
?>
Professional Naming Conventions
Beyond the technical requirements, the PHP community has developed naming conventions that make code more readable, maintainable, and professional. These aren't enforced by PHP itself, but following them makes your code easier to understand and work with in team environments.
Use descriptive names that explain purpose: Variable names should clearly communicate what data they contain and how it's intended to be used.
<?php
// Poor naming - unclear purpose and content
$d = '2024-06-17'; // What kind of date?
$amt = 99.99; // Amount of what?
$flag = true; // Flag for what condition?
// Better naming - self-documenting
$orderDate = '2024-06-17';
$productPrice = 99.99;
$isEligibleForDiscount = true;
echo "Order from $orderDate<br>";
echo "Product costs $" . number_format($productPrice, 2) . "<br>";
echo "Discount eligible: " . ($isEligibleForDiscount ? "Yes" : "No") . "<br>";
?>
Use consistent naming style: Pick either camelCase or snake_case and stick with it throughout your project. Boolean variables should indicate true/false nature: Use prefixes like is
, has
, can
, or should
to make it clear that a variable represents a yes/no condition.
Variable Scope
Variable scope is one of the most important concepts in programming because it determines where in your code a variable can be accessed and how long it stays in memory. Understanding scope helps you write more organized code, avoid naming conflicts, and prevent bugs caused by accidentally modifying the wrong variable.
Think of scope as the "visibility rules" for variables. Just like you can only see certain things from certain locations in the physical world, variables are only "visible" (accessible) from certain parts of your code.
Global Scope
Variables declared outside of any function exist in global scope. These variables are created when your script starts running and remain accessible throughout the entire script execution, but accessing them from within functions requires special handling.
<?php
// These variables exist in global scope
$siteName = "My Online Store";
$totalVisitors = 0;
$maintenanceMode = false;
function trackVisitor() {
// Must explicitly request access with 'global' keyword
global $siteName, $totalVisitors;
$totalVisitors++;
echo "Welcome to $siteName! You are visitor #$totalVisitors<br>";
}
trackVisitor();
trackVisitor();
echo "Site: $siteName<br>";
echo "Total visitors: $totalVisitors<br>";
?>
The global
keyword is PHP's way of saying "I want to access the global variable with this name, not create a new local variable." This explicit requirement prevents functions from accidentally modifying global variables.
Local Scope
Variables declared inside functions exist only within that function's local scope. This means they're created when the function starts executing and automatically destroyed when the function finishes.
<?php
function calculateOrderTotal($basePrice, $taxRate, $discountPercent) {
// These variables only exist inside this function
$discount = $basePrice * ($discountPercent / 100);
$discountedPrice = $basePrice - $discount;
$tax = $discountedPrice * $taxRate;
$finalTotal = $discountedPrice + $tax;
echo "Base price: $" . number_format($basePrice, 2) . "<br>";
echo "Discount: $" . number_format($discount, 2) . "<br>";
echo "Tax: $" . number_format($tax, 2) . "<br>";
return $finalTotal;
}
$orderAmount = calculateOrderTotal(100.00, 0.08, 10);
echo "Order total: $" . number_format($orderAmount, 2) . "<br>";
// These variables don't exist outside the function:
// echo $discount; // Would cause an error
?>
Local scope creates isolated environments where functions can work without worrying about what other parts of the program are doing.
Static Variables
Static variables are a special type of local variable that "remembers" its value between function calls. While normal local variables are destroyed when a function ends, static variables persist in memory and retain their value for the next time the function is called.
<?php
function generateInvoiceNumber() {
static $invoiceCounter = 1000; // Initialized only once, ever
$invoiceCounter++;
$invoiceNumber = "INV-" . date('Y') . "-" . str_pad($invoiceCounter, 4, "0", STR_PAD_LEFT);
return $invoiceNumber;
}
// Each call remembers the previous value
echo "Invoice 1: " . generateInvoiceNumber() . "<br>";
echo "Invoice 2: " . generateInvoiceNumber() . "<br>";
echo "Invoice 3: " . generateInvoiceNumber() . "<br>";
?>
Static variables solve the problem of needing persistent data without cluttering the global scope. They're particularly useful for generating unique IDs, implementing simple caches, or tracking function usage statistics.
Superglobal Variables
Superglobal variables are special arrays that PHP provides automatically in every script. They're called "superglobal" because they're available in all scopes without needing the global
keyword - they break the normal scope rules because they contain essential information that web applications frequently need.
These variables serve as the communication bridge between your PHP code and the web environment. The most important superglobals for web development include $_GET
, $_POST
, $_SERVER
, $_SESSION
, and $_COOKIE
.
<?php
// $_SERVER contains extensive server and request information
echo "<h3>Server Information:</h3>";
echo "Server software: " . ($_SERVER['SERVER_SOFTWARE'] ?? 'Not available') . "<br>";
echo "Request method: " . ($_SERVER['REQUEST_METHOD'] ?? 'Not available') . "<br>";
echo "Script name: " . ($_SERVER['SCRIPT_NAME'] ?? 'Not available') . "<br>";
// Example of typical superglobal usage
$page = $_GET['page'] ?? 1;
$username = $_POST['username'] ?? '';
$userID = $_SESSION['user_id'] ?? null;
echo "<h3>Typical Usage:</h3>";
echo "Current page: $page<br>";
echo "Username: " . ($username ?: 'Not provided') . "<br>";
echo "User ID: " . ($userID ?? 'Not logged in') . "<br>";
?>
Critical security note: Always validate and sanitize data from superglobals that contain user input. Never trust user input directly - it could contain malicious code or unexpected values.
Constants: Values That Never Change
Constants in programming represent values that remain fixed throughout your program's execution. Unlike variables, which are designed to vary, constants provide stability and predictability. Once you define a constant, attempting to change its value will result in an error.
Constants serve several important purposes: they prevent accidental modification of important values, they make your code more readable by giving meaningful names to fixed values, and they help catch bugs if you try to change a constant.
Creating Constants
PHP offers two distinct ways to create constants, each with specific use cases and limitations.
<?php
// Method 1: Using define() function
define('SITE_NAME', 'My E-Commerce Store');
define('MAX_LOGIN_ATTEMPTS', 3);
define('VERSION', '2.1.0');
// Method 2: Using const keyword
const TAX_RATE = 0.08;
const CURRENCY_SYMBOL = '$';
const DEBUG_ENABLED = true;
// Using constants (no $ sign needed)
echo "Welcome to " . SITE_NAME . "<br>";
echo "Version: " . VERSION . "<br>";
echo "Max login attempts: " . MAX_LOGIN_ATTEMPTS . "<br>";
echo "Tax rate: " . (TAX_RATE * 100) . "%<br>";
?>
Both methods create constants, but they work differently. The define()
function executes at runtime, while the const
keyword is processed at compile time.
Differences Between define() and const
Timing differences: The const
keyword is processed during the compilation phase, before your code actually runs. The define()
function executes during runtime, which means you can create constants conditionally.
Scope limitations: The const
keyword can only be used at the top level of your script. The define()
function can be used anywhere in your code.
<?php
// const must be used at the top level
const APP_NAME = 'My Application';
function initializeApplication($environment) {
// define() works inside functions
define('CURRENT_ENVIRONMENT', $environment);
define('LOG_LEVEL', $environment === 'production' ? 'error' : 'debug');
}
initializeApplication('development');
echo "App: " . APP_NAME . "<br>";
echo "Environment: " . CURRENT_ENVIRONMENT . "<br>";
echo "Log level: " . LOG_LEVEL . "<br>";
?>
Use const
for simple, fixed values. Use define()
when you need to create constants based on runtime conditions or inside functions.
Magic Constants
Magic constants are special constants that change their value depending on where they're used in your code. Unlike regular constants that always have the same value, magic constants are "context-aware" - they know information about the current file, line number, function, or class they're in.
<?php
echo "I'm on line " . __LINE__ . " of this script<br>";
echo "This file is called: " . basename(__FILE__) . "<br>";
echo "This file is in directory: " . basename(__DIR__) . "<br>";
function debugFunction() {
echo "<br>Debug info from inside the function:<br>";
echo "Now I'm on line " . __LINE__ . "<br>";
echo "I'm inside the function: " . __FUNCTION__ . "<br>";
}
debugFunction();
?>
Magic constants are incredibly useful for debugging, error reporting, and building file paths that work no matter where your application is installed. When an error occurs, instead of just saying "something broke," you can say exactly which file and line number caused the problem.
Variable Variables
Variable variables are an advanced PHP feature that allows you to use the value stored in one variable as the name of another variable. This creates a level of indirection - instead of directly accessing a variable, you're accessing a variable whose name is determined by another variable's value.
The syntax uses double dollar signs ($$
). When PHP sees $$variableName
, it first looks at the value stored in $variableName
, then uses that value as the name of another variable to access.
<?php
// Basic variable variables demonstration
$animalType = 'cat';
$cat = 'Whiskers';
$dog = 'Buddy';
// $$animalType means "the variable named by the value in $animalType"
echo "The $animalType is named: " . $$animalType . "<br>";
// Change which animal we're referring to
$animalType = 'dog';
echo "The $animalType is named: " . $$animalType . "<br>";
// Practical example: dynamic form processing
$formFields = ['user_name', 'user_email', 'user_phone'];
$user_name = 'Alice Johnson';
$user_email = '[email protected]';
$user_phone = '555-1234';
echo "<br>User Information:<br>";
foreach ($formFields as $fieldName) {
$fieldValue = $$fieldName;
$displayName = ucwords(str_replace('_', ' ', $fieldName));
echo "$displayName: $fieldValue<br>";
}
?>
Variable variables can make code harder to understand and debug. Use them sparingly and consider arrays or objects as alternatives in most cases.
Best Practices
Following established practices makes your code more maintainable and reduces bugs. These practices have evolved from decades of collective developer experience.
Initialize Variables Properly
Always give variables sensible default values that match their intended purpose. This practice makes your code more predictable and prevents undefined variable warnings.
<?php
// Good practice: Initialize variables with appropriate defaults
$totalRevenue = 0.00;
$errorMessages = [];
$isDataValid = false;
$processingStatus = 'pending';
// Simulate business logic
$salesData = [150.00, 200.00, 75.50];
$hasValidData = !empty($salesData);
if ($hasValidData) {
foreach ($salesData as $sale) {
if ($sale > 0) {
$totalRevenue += $sale;
} else {
$errorMessages[] = "Invalid sale amount: $sale";
}
}
$isDataValid = empty($errorMessages);
$processingStatus = $isDataValid ? 'completed' : 'completed_with_errors';
} else {
$errorMessages[] = 'No sales data available';
$processingStatus = 'failed';
}
echo "Total revenue: $" . number_format($totalRevenue, 2) . "<br>";
echo "Data valid: " . ($isDataValid ? 'Yes' : 'No') . "<br>";
echo "Status: $processingStatus<br>";
echo "Error count: " . count($errorMessages) . "<br>";
?>
Use Meaningful Names
Variable and constant names are your primary tool for communicating intent to other developers. Invest time in choosing descriptive names that make your code self-documenting.
<?php
// Poor naming - forces readers to guess meaning
$d = '2024-06-17';
$amt = 149.99;
$flag = true;
// Better naming - self-documenting and clear
$orderShippingDate = '2024-06-17';
$productPriceInUSD = 149.99;
$isEligibleForFreeShipping = true;
echo "Shipping date: $orderShippingDate<br>";
echo "Price: $" . number_format($productPriceInUSD, 2) . " USD<br>";
echo "Free shipping eligible: " . ($isEligibleForFreeShipping ? 'Yes' : 'No') . "<br>";
?>
Organize Constants Logically
Group related constants together and use consistent naming patterns that indicate their category and purpose.
<?php
// Application metadata
const APP_NAME = 'E-Commerce Platform';
const APP_VERSION = '2.1.0';
const APP_ENVIRONMENT = 'development';
// Business rules
const MIN_ORDER_AMOUNT = 25.00;
const FREE_SHIPPING_THRESHOLD = 75.00;
const MAX_ITEMS_PER_ORDER = 50;
// Security settings
const MAX_LOGIN_ATTEMPTS = 3;
const SESSION_TIMEOUT_MINUTES = 30;
const PASSWORD_MIN_LENGTH = 8;
echo APP_NAME . " v" . APP_VERSION . "<br>";
echo "Min order: $" . number_format(MIN_ORDER_AMOUNT, 2) . "<br>";
echo "Max login attempts: " . MAX_LOGIN_ATTEMPTS . "<br>";
echo "Session timeout: " . SESSION_TIMEOUT_MINUTES . " minutes<br>";
?>
Common Pitfalls
Understanding frequent mistakes helps you write better code from the start.
Undefined Variable Warnings
Modern PHP generates warnings when you use undefined variables. Always initialize variables or use proper checks.
<?php
// Better approaches:
// Method 1: Initialize variables
$searchTerm = '';
if (isset($_GET['search'])) {
$searchTerm = $_GET['search'];
}
// Method 2: Use null coalescing operator
$page = $_GET['page'] ?? 1;
$itemsPerPage = $_GET['limit'] ?? 10;
echo "Search: " . ($searchTerm ?: 'None') . "<br>";
echo "Page: $page<br>";
echo "Items per page: $itemsPerPage<br>";
?>
Case Sensitivity Issues
Inconsistent capitalization creates different variables, leading to confusing bugs.
<?php
// Problem: These are all different variables
$userName = 'Alice';
$UserName = 'Bob';
$username = 'Charlie';
// Solution: Pick one style and be consistent
$userFirstName = 'David';
$userLastName = 'Wilson';
$userFullName = $userFirstName . ' ' . $userLastName;
echo "Consistent naming: $userFullName";
?>
Global Variable Overuse
Avoid unnecessary global variables. Use function parameters and return values instead for cleaner, more maintainable code.
Practical Example: User Preferences
Let's apply these concepts in a realistic scenario for managing user preferences:
<?php
// Configuration constants
const DEFAULT_THEME = 'light';
const DEFAULT_LANGUAGE = 'en';
const AVAILABLE_THEMES = ['light', 'dark', 'auto'];
// Initialize user preference variables
$userTheme = '';
$userLanguage = '';
$notifications = false;
$errors = [];
// Simulate user input (normally from $_POST or database)
$userInput = [
'theme' => 'dark',
'language' => 'en',
'notifications' => 'on'
];
// Process theme preference
$requestedTheme = $userInput['theme'] ?? DEFAULT_THEME;
if (in_array($requestedTheme, AVAILABLE_THEMES)) {
$userTheme = $requestedTheme;
} else {
$userTheme = DEFAULT_THEME;
$errors[] = 'Invalid theme selected, using default';
}
// Process language preference
$userLanguage = $userInput['language'] ?? DEFAULT_LANGUAGE;
if (strlen($userLanguage) !== 2) {
$userLanguage = DEFAULT_LANGUAGE;
$errors[] = 'Invalid language code, using default';
}
// Process notification preference
$notifications = isset($userInput['notifications']) && $userInput['notifications'] === 'on';
// Display results
if (empty($errors)) {
echo "<div style='color: green;'>✓ Preferences saved successfully!</div>";
} else {
echo "<div style='color: orange;'>⚠ Saved with warnings:</div>";
foreach ($errors as $error) {
echo "<div style='margin-left: 20px;'>• $error</div>";
}
}
echo "<br><strong>User Preferences:</strong><br>";
echo "Theme: $userTheme<br>";
echo "Language: $userLanguage<br>";
echo "Notifications: " . ($notifications ? 'Enabled' : 'Disabled') . "<br>";
?>
This example demonstrates proper variable initialization, input validation, constant usage, and error handling using the concepts we've covered.
Moving Forward
Variables and constants are fundamental building blocks you'll use in every PHP application. Mastering these concepts now provides a solid foundation for more advanced topics ahead.
In our next lesson, we'll explore PHP's type declaration system. You'll learn how to specify what types of data your variables should contain, adding an extra layer of reliability and clarity to your code.
The habits you develop around variable naming, initialization, and scope management will serve you throughout your PHP development journey. Take time to practice these concepts and establish good patterns early - your future self will thank you for the clarity and maintainability.
← Previous Lesson: Basic Data Types Next Lesson: Type Declarations →