Variables And Constants
Programs become useful when values have names. A variable names a value that belongs to the current execution and may change as the program performs work. A constant names a value that should remain stable after it is defined.
Good names make code explain its data. $priceCents communicates more than $price, and MAX_ITEMS_PER_ORDER communicates more than LIMIT.
Assign A Value To A Variable
PHP variable names begin with $:
<?php
$productName = 'PHP Workbook';
$priceCents = 2499;
echo $productName, PHP_EOL;
echo $priceCents, PHP_EOL;
The assignment operator = stores the value on its right under the variable name on its left. Read $productName = 'PHP Workbook'; as "assign the string PHP Workbook to $productName," not as a mathematical equality claim.
After assignment, later statements can read the value by using the same variable name:
<?php
$courseName = 'PHP From Zero';
echo $courseName, PHP_EOL;
echo $courseName, PHP_EOL;
Both echo statements read the current value of $courseName. Reuse is one reason to name data instead of repeating a literal throughout the program.
Choose Names That Carry Meaning
A variable name can contain letters, digits, and underscores, but it cannot begin with a digit after $. These are conventional camelCase names:
<?php
$customerName = 'Grace';
$orderCount = 3;
$isReady = true;
Names should answer questions about the value:
$customerNameidentifies whose name it is;$orderCountsays the number represents orders;$priceCentsincludes the monetary unit;$createdAtsuggests a creation timestamp;$isReadyreads like a yes-or-no state.
Avoid vague names such as $data, $value, $thing, or $x when a domain name is available. Very short names are reasonable in a tiny mathematical expression or a familiar loop, but application state deserves descriptive names.
Do not encode a type into a name mechanically. $customerNames usefully indicates a collection because the plural changes meaning; $stringCustomerName usually adds noise and becomes misleading if the representation changes.
Variable Names Are Case-Sensitive
These are different variables:
<?php
$customerName = 'Grace';
$customername = 'Ada';
echo $customerName, PHP_EOL;
echo $customername, PHP_EOL;
The output is:
Grace
Ada
A case mismatch is therefore not cosmetic. If you assign $customerName and later read $customername, PHP treats the second spelling as another name. In modern PHP, reading an undefined variable produces a warning and the expression commonly continues with null, which can cause misleading output after the warning.
Use one naming convention consistently and let an editor, static analyser, and tests help catch misspellings.
Print Variables With Interpolation
Double-quoted strings can interpolate variables:
<?php
$productName = 'PHP Workbook';
$priceCents = 2499;
echo "$productName costs $priceCents cents\n";
Output:
PHP Workbook costs 2499 cents
PHP replaces each recognised variable reference with its current value.
Use braces when adjacent characters could be mistaken as part of the variable name:
<?php
$quantity = 3;
echo "Ordered: {$quantity}x\n";
Without braces, $quantityx would be read as a different variable name. Braces make the intended boundary explicit.
Single-quoted strings do not interpolate variables:
<?php
$name = 'Ada';
echo '$name', PHP_EOL;
This prints the literal characters $name. Choose double quotes when interpolation or escape sequences are intentional. Choose single quotes for literal text where interpolation is not wanted.
Concatenate Values Explicitly
The dot operator joins strings and printable values:
<?php
$name = 'Ada';
$role = 'developer';
echo $name . ' works as a ' . $role . '.' . PHP_EOL;
Output:
Ada works as a developer.
Concatenation is useful when a value sits outside a string or when single-quoted literal pieces make boundaries clearer.
Do not use + to join text. In PHP, + is an arithmetic operator. The operators lesson covers those rules in detail; for string joining, use . or a clearly interpolated double-quoted string.
Reassignment Changes Current State
A variable can receive a new value:
<?php
$orderStatus = 'pending';
echo "Status: $orderStatus\n";
$orderStatus = 'paid';
echo "Status: $orderStatus\n";
Output:
Status: pending
Status: paid
The second assignment does not create a history automatically. It replaces the current value associated with $orderStatus. If the program needs both values, give them separate names:
<?php
$previousStatus = 'pending';
$currentStatus = 'paid';
Reassignment should represent a real state transition, not uncertainty about naming. Reusing one variable for unrelated meanings makes code difficult to follow:
$result = 'Ada';
$result = 42;
$result = true;
Even though PHP can store different kinds of values in a variable, one name should keep one coherent meaning during a section of code.
Copy Simple Values Deliberately
Assigning one simple value variable to another gives the second variable that current value:
<?php
$originalStatus = 'pending';
$currentStatus = $originalStatus;
$currentStatus = 'paid';
echo "Original: $originalStatus\n";
echo "Current: $currentStatus\n";
Output:
Original: pending
Current: paid
Changing $currentStatus did not rename or overwrite $originalStatus. PHP references and object behavior add other rules later, but ordinary beginner code should not assume that two different variable names are secretly linked.
Initialise Before Reading
Assign a variable before using it:
<?php
$message = 'No orders found';
echo $message, PHP_EOL;
Do not rely on an undefined variable becoming an empty-looking value after a warning. Warnings are evidence of a broken assumption, and production error display settings can hide them while the bad behavior remains.
When a value is optional, model that choice explicitly in later code with a default, null, a condition, or validated input. Do not create optional behavior by misspelling or skipping an assignment.
Use Constants For Stable Program Rules
A constant is referenced without $:
<?php
const CURRENCY = 'GBP';
const MAX_ITEMS_PER_ORDER = 20;
echo CURRENCY, PHP_EOL;
echo MAX_ITEMS_PER_ORDER, PHP_EOL;
By convention, application constant names use uppercase words separated by underscores. The style makes a stable rule visually distinct from a variable.
A constant cannot be reassigned during the request:
const CURRENCY = 'GBP';
CURRENCY = 'USD';
The second line is not valid assignment syntax. If a value genuinely needs to change while the program runs, it should be a variable instead.
Good beginner constant candidates include a fixed application identifier, a deliberate batch limit, or a stable unit used by that code. Do not turn every literal into a constant. A value used once, such as a single output label, may be clearer inline.
const And define()
PHP also provides define():
<?php
define('APPLICATION_NAME', 'PHP From Zero');
echo APPLICATION_NAME, PHP_EOL;
For straightforward declarations known while writing the file, const is usually clearer and easier for tools to analyse:
<?php
const APPLICATION_NAME = 'PHP From Zero';
define() is a runtime function and can be useful when the constant name or declaration decision is produced dynamically, though dynamically named global constants are uncommon in well-structured application code.
Do not define the same constant twice. PHP warns because the first definition has already established the name for that process.
Do Not Confuse Constants With Configuration
A database host, API endpoint, feature flag, or deployment environment may stay unchanged during one request but differ between machines or deployments. That does not automatically make it a source-code constant.
Configuration normally comes from a controlled configuration file, environment mechanism, or dependency container and is validated at application startup. Hard-coding deployment-specific values as global constants makes testing and deployment changes harder.
Use a constant for a rule that belongs to the code. Use configuration for a value supplied by the environment. Use a variable for state held by the current execution.
Avoid Variable Variables In Beginner Code
PHP can interpret the value of one variable as another variable's name, but that feature obscures which data a script uses. Prefer an array or explicit mapping when selecting values by a dynamic key.
This direct code is easy to trace:
<?php
$customerName = 'Grace';
echo $customerName, PHP_EOL;
A naming feature is not automatically a good design choice. Predictable, statically visible variable names work better with readers, editors, analysers, and refactoring tools.
Common Variable And Constant Mistakes
| Symptom | Likely cause |
|---|---|
| Undefined variable warning | Name was never assigned or case does not match |
Literal $name appears |
Variable was placed in a single-quoted string |
Warning for $quantityx |
Interpolation boundary needed {$quantity}x |
| Text addition behaves unexpectedly | + was used instead of string concatenation . |
| Constant appears undefined | $ was added, spelling differs, or declaration did not run |
| Constant redefinition warning | Same global constant name was declared twice |
| One variable changes meaning repeatedly | Distinct concepts need distinct names |
What You Should Be Able To Do
After this lesson, you should be able to assign and read variables, choose descriptive case-consistent names, interpolate or concatenate values, explain reassignment, avoid undefined-variable behavior, declare constants with const, recognise define(), and choose among a variable, code constant, and deployment configuration based on the value's role.
Practice
Practice: Build A Profile Report
- a person's name
- their job title
- completed lesson count
- study time in minutes
Use descriptive camelCase names, including the unit in $studyMinutes.
Print exactly four labelled lines:
Name: Ada Lovelace
Role: PHP developer
Progress: 3 lessons
Study time: 45 minutes
Requirements:
- use double-quoted interpolation for at least two lines
- use concatenation for at least one line
- use braced interpolation in
{$completedLessons} lessons - include a final newline
- lint and execute the file
Afterward, explain why $studyMinutes is clearer than $studyTime and why braces make the interpolation boundary explicit.
Show solution
<?php
$name = 'Ada Lovelace';
$jobTitle = 'PHP developer';
$completedLessons = 3;
$studyMinutes = 45;
echo "Name: $name\n";
echo 'Role: ' . $jobTitle . PHP_EOL;
echo "Progress: {$completedLessons} lessons\n";
echo "Study time: $studyMinutes minutes\n";
Output:
Name: Ada Lovelace
Role: PHP developer
Progress: 3 lessons
Study time: 45 minutes
$studyMinutes records the unit in the name, so a later reader does not have to guess whether 45 means seconds, minutes, or hours. Braces around $completedLessons clearly end the variable reference before the following space and noun, and the same syntax remains useful when text touches a variable directly.
Practice: Fix Variable Identity Bugs
<?php
$customerName = 'Grace';
$itemCount = 2;
echo "$customername placed an order.\n";
echo "Packed: $itemCountitems\n";
Task
- run
php -land explain why lint succeeds - execute the script and record both warnings
- fix the case mismatch without renaming the original variable
- use braced interpolation so the second line prints
Packed: 2 items - run the syntax and execution checks again
The final output must be:
Grace placed an order.
Packed: 2 items
Afterward, name the undefined variable PHP tried to read on each broken line.
Show solution
<?php
$customerName = 'Grace';
$itemCount = 2;
echo "$customerName placed an order.\n";
echo "Packed: {$itemCount} items\n";
Output:
Grace placed an order.
Packed: 2 items
Lint succeeds on the broken script because both $customername and $itemCountitems are legal variable-name tokens. Syntax validation cannot know that the programmer intended different names.
The first broken line reads $customername, which is distinct from the assigned $customerName because variable names are case-sensitive. The second reads one variable named $itemCountitems; PHP continues consuming valid name characters after $itemCount. Braces change the boundary to {$itemCount}, leaving items as ordinary string text.
Practice: Separate Rules From State
- constant
CURRENCYset toGBP - constant
MAX_ITEMS_PER_ORDERset to20 - variable
$itemsPerPageinitially set to25
Print one settings line, reassign $itemsPerPage to 50, then print a second line.
Expected output:
Currency: GBP; max order items: 20; page size: 25
Currency: GBP; max order items: 20; page size: 50
Requirements:
- declare constants with
const - use uppercase underscore-separated constant names
- reference constants without
$ - demonstrate that only the variable changes
- use either interpolation plus concatenation or comma-separated
echovalues - lint and execute the file
Afterward, explain why the currency and maximum are code rules in this exercise, why page size is mutable state, and why a production database password should be configuration rather than a source-code constant.
Show solution
<?php
const CURRENCY = 'GBP';
const MAX_ITEMS_PER_ORDER = 20;
$itemsPerPage = 25;
echo 'Currency: ', CURRENCY,
'; max order items: ', MAX_ITEMS_PER_ORDER,
"; page size: $itemsPerPage\n";
$itemsPerPage = 50;
echo 'Currency: ', CURRENCY,
'; max order items: ', MAX_ITEMS_PER_ORDER,
"; page size: $itemsPerPage\n";
Output:
Currency: GBP; max order items: 20; page size: 25
Currency: GBP; max order items: 20; page size: 50
The currency and maximum represent stable rules chosen for this exercise, so changing either during execution would be a programming error. Page size represents a current choice and is therefore stored in a variable that can be reassigned.
A production database password varies by environment and must be supplied and protected as configuration. Embedding it in a source-code constant would expose a secret in the repository and make deployment-specific changes require code edits.