Programming languages · Intermediate · 25 min
Write safer PHP with strict types, enums and readonly classes
By Padding · Updated 18 Nov 2026
PHP 8.5.13 · Composer 2.11 · PHPStan 2.3 · php:8.5-cli image (Debian 13)
You will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
On this page
PHP will try hard to keep a script running. Give a function that expects an int the string "1.5" and, by default, PHP turns it into 1 and carries on. Compare a status with switch and a typo falls through to default without a word. Neither is a crash, which is the problem: the script finishes, the report looks fine, and the numbers are wrong.
Modern PHP gives you the tools to make those mistakes loud. In this tutorial you start with a short script that reads a shop's orders from a CSV file and prints a revenue report. It has four quiet bugs. You fix them one tool at a time: declare(strict_types=1), union and nullable types, match, a backed enum for the order status, readonly classes for money and orders, and first-class callable syntax. Then you run PHPStan, a static analyser, to find the bugs that are still hiding before the code ever runs.
The shop sells groceries in Nigeria, so prices are stored in kobo (100 kobo to the naira) as whole numbers. Keeping money in the smallest unit as an integer avoids the rounding errors of floats, and the same approach works for cents, pesewas or shillings.
You need PHP 8.5 from the Hello World in PHP tutorial and Composer from the Composer tutorial. PHP 8.6 was released on 19 November 2026; everything here works the same on it. You work in a throwaway folder, ~/php-orders-demo, and delete it at the end.
Step 1 · Run the loose order script
Make the folder and add a small CSV export of five orders. Each row has an order ID, a status, a product code, a quantity, a unit price in kobo and an optional coupon code:
mkdir -p ~/php-orders-demo
cd ~/php-orders-demo
cat > orders.csv <<'CSV'
id,status,sku,quantity,unit_price_kobo,coupon
A-1001,paid,RICE-5KG,2,750000,
A-1002,pending,BEANS-2KG,1.5,410000,
A-1003,shipped,SUGAR-1KG,3,150000,save10
A-1004,Paid,OIL-1L,1,320000,
A-1005,refunded,RICE-5KG,1,750000,
CSVNow the script, written the way a lot of older PHP is. It has type declarations on lineTotal, but nothing on statusLabel, and it trusts every value in the file:
cd ~/php-orders-demo
cat > orders.php <<'PHP'
<?php
function lineTotal(int $quantity, int $unitPriceKobo): int
{
return $quantity * $unitPriceKobo;
}
function statusLabel($status)
{
switch ($status) {
case 'pending':
return 'Waiting for payment';
case 'paid':
return 'Ready to pack';
case 'shipped':
return 'On the way';
default:
return 'Unknown';
}
}
$lines = file(__DIR__ . '/orders.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$total = 0;
foreach (array_slice($lines, 1) as $line) {
[$id, $status, $sku, $quantity, $price, $coupon] = explode(',', $line);
$amount = lineTotal($quantity, $price);
$total += $amount;
printf("%s %-10s %-20s %12s\n", $id, $sku, statusLabel($status), number_format($amount / 100, 2));
}
printf("Total: NGN %s\n", number_format($total / 100, 2));
PHP
php orders.phpCheck it worked
The script runs to the end and prints five lines and Total: NGN 34,300.00. Depending on your php.ini, you may also see Deprecated: Implicit conversion from float-string "1.5" to int loses precision. Look at what went wrong without an error:
- A-1002 asked for 1.5 bags of beans. PHP converted
"1.5"to1and charged for one bag. - A-1004 has the status
Paidwith a capital P, soswitchfell through toUnknown. - A-1003 has a coupon that the script ignores.
- The total includes a pending order and a refunded one, which are not revenue.
Step 2 · Turn on strict types
Add declare(strict_types=1); as the first statement in the file. It changes one rule: in calls made from this file, a scalar argument must already be the declared type. PHP stops converting "2" to 2 for you and throws a TypeError instead. The only conversion it still allows is an int passed where a float is expected.
Write the declaration into a fresh copy of the script, keeping everything after the opening tag:
cd ~/php-orders-demo
{ printf '<?php\n\ndeclare(strict_types=1);\n'; tail -n +2 orders.php; } > orders-strict.php
mv orders-strict.php orders.php
head -n 5 orders.php
php orders.php || echo "php exited with status $?"The setting is per file. It applies to calls written in orders.php and to the return values of functions declared there, not to code in other files. That is why every file you write from here on starts with the same line.
Check it worked
The first lines of the file now read <?php, a blank line and declare(strict_types=1);. The run stops at the first order with Fatal error: Uncaught TypeError: lineTotal(): Argument #1 ($quantity) must be of type int, string given, followed by a stack trace, and the shell reports status 255. Every value from explode is a string, and PHP no longer pretends otherwise.
Step 3 · Parse input at the edge with union and nullable types
Strict types move the conversion to one place: the moment data enters the program. Write two parsing functions in their own file. parseWholeNumber takes int|string, a union type, so it accepts a value that is already an integer (from JSON, say) as well as text from the CSV, and it refuses anything that is not a whole number. parseCoupon returns ?string, a nullable type: a code, or null when the column is empty. The ? makes "no coupon" part of the signature, so callers have to deal with it.
cd ~/php-orders-demo
mkdir -p src
cat > src/parse.php <<'PHP'
<?php
declare(strict_types=1);
function parseWholeNumber(int|string $raw, string $field): int
{
if (is_int($raw)) {
return $raw;
}
$value = filter_var(trim($raw), FILTER_VALIDATE_INT);
if ($value === false) {
throw new InvalidArgumentException(sprintf('%s must be a whole number, got "%s"', $field, $raw));
}
return $value;
}
function parseCoupon(string $raw): ?string
{
$code = strtoupper(trim($raw));
return $code === '' ? null : $code;
}
PHPNow rewrite the script to use them. lineTotal gains a ?string $coupon parameter and applies 10 per cent off for SAVE10. A row that fails to parse is reported and skipped instead of stopping the whole run. The script also checks the result of file(), which returns false if the file cannot be read:
cd ~/php-orders-demo
cat > orders.php <<'PHP'
<?php
declare(strict_types=1);
require_once __DIR__ . '/src/parse.php';
function lineTotal(int $quantity, int $unitPriceKobo, ?string $coupon): int
{
$gross = $quantity * $unitPriceKobo;
return $coupon === 'SAVE10' ? intdiv($gross * 90, 100) : $gross;
}
function statusLabel($status)
{
switch ($status) {
case 'pending':
return 'Waiting for payment';
case 'paid':
return 'Ready to pack';
case 'shipped':
return 'On the way';
default:
return 'Unknown';
}
}
$lines = file(__DIR__ . '/orders.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
throw new RuntimeException('Cannot read orders.csv');
}
$total = 0;
foreach (array_slice($lines, 1) as $line) {
[$id, $status, $sku, $quantity, $price, $coupon] = explode(',', $line);
try {
$amount = lineTotal(
parseWholeNumber($quantity, 'quantity'),
parseWholeNumber($price, 'unit_price_kobo'),
parseCoupon($coupon),
);
} catch (InvalidArgumentException $e) {
printf("%s skipped: %s\n", $id, $e->getMessage());
continue;
}
$total += $amount;
printf("%s %-10s %-20s %12s\n", $id, $sku, statusLabel($status), number_format($amount / 100, 2));
}
printf("Total: NGN %s\n", number_format($total / 100, 2));
PHP
php orders.phpCheck it worked
The output has A-1002 skipped: quantity must be a whole number, got "1.5", A-1003 now costs 4,050.00 with its coupon, and the total is NGN 29,750.00. There is no deprecation notice any more, because no implicit conversion happens. Two bugs are left: A-1004 still shows Unknown, and the total still counts orders that are not paid.
Step 4 · Replace switch with match
switch compares with ==, falls through to the next case if you forget a return or break, and quietly does nothing, or runs default, for a value you did not expect. match is an expression that returns a value, compares with ===, never falls through, and throws an UnhandledMatchError when no arm fits. Replace statusLabel with a typed match version and leave out a default arm on purpose:
cd ~/php-orders-demo
cat > status-label.php <<'PHP'
<?php
declare(strict_types=1);
function statusLabel(string $status): string
{
return match ($status) {
'pending' => 'Waiting for payment',
'paid' => 'Ready to pack',
'shipped' => 'On the way',
};
}
PHP
php -r 'require "status-label.php"; echo statusLabel("paid"), "\n"; echo statusLabel("Paid"), "\n";' || echo "php exited with status $?"This is only a trial file. In the next step the labels move onto an enum, where match really pays off.
Check it worked
The first call prints Ready to pack. The second stops with Fatal error: Uncaught UnhandledMatchError: Unhandled match case followed by 'Paid' or "Paid", depending on the exact 8.5 release. The typo that switch hid as Unknown is now an error that names the bad value.
Step 5 · Model the order status with a backed enum
A status is one of a fixed set of values, so make it a type. A backed enum is a type whose cases each carry a scalar value, here the string used in the CSV. OrderStatus::from('paid') returns the Paid case and throws a ValueError for anything else. OrderStatus::tryFrom() returns null instead of throwing, which suits input you have not checked yet. Enums can have methods, and a match over $this that names every case is easy to check by eye and by tools.
Write the enum. fromInput tidies the raw text (so Paid and paid ` both work) and turns an unknown status into the same `InvalidArgumentException the parsers throw:
cd ~/php-orders-demo
cat > src/OrderStatus.php <<'PHP'
<?php
declare(strict_types=1);
enum OrderStatus: string
{
case Pending = 'pending';
case Paid = 'paid';
case Shipped = 'shipped';
case Cancelled = 'cancelled';
public static function fromInput(string $raw): self
{
return self::tryFrom(strtolower(trim($raw)))
?? throw new InvalidArgumentException(sprintf('unknown status "%s"', $raw));
}
public function label(): string
{
return match ($this) {
self::Pending => 'Waiting for payment',
self::Paid => 'Ready to pack',
self::Shipped => 'On the way',
self::Cancelled => 'Cancelled',
};
}
public function countsTowardsRevenue(): bool
{
return match ($this) {
self::Paid, self::Shipped => true,
self::Pending, self::Cancelled => false,
};
}
}
PHP
php -r 'require "src/OrderStatus.php"; var_dump(OrderStatus::tryFrom("refunded")); echo OrderStatus::fromInput(" Paid ")->label(), "\n"; echo implode(", ", array_column(OrderStatus::cases(), "value")), "\n";'Now use it in the script. The status is parsed with the other fields, so an unknown status skips the row, and only paid or shipped orders count towards revenue. Remove the trial file too:
cd ~/php-orders-demo
rm status-label.php
cat > orders.php <<'PHP'
<?php
declare(strict_types=1);
require_once __DIR__ . '/src/parse.php';
require_once __DIR__ . '/src/OrderStatus.php';
function lineTotal(int $quantity, int $unitPriceKobo, ?string $coupon): int
{
$gross = $quantity * $unitPriceKobo;
return $coupon === 'SAVE10' ? intdiv($gross * 90, 100) : $gross;
}
$lines = file(__DIR__ . '/orders.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
throw new RuntimeException('Cannot read orders.csv');
}
$revenue = 0;
foreach (array_slice($lines, 1) as $line) {
[$id, $status, $sku, $quantity, $price, $coupon] = explode(',', $line);
try {
$status = OrderStatus::fromInput($status);
$amount = lineTotal(
parseWholeNumber($quantity, 'quantity'),
parseWholeNumber($price, 'unit_price_kobo'),
parseCoupon($coupon),
);
} catch (InvalidArgumentException $e) {
printf("%s skipped: %s\n", $id, $e->getMessage());
continue;
}
if ($status->countsTowardsRevenue()) {
$revenue += $amount;
}
printf("%s %-10s %-20s %12s\n", $id, $sku, $status->label(), number_format($amount / 100, 2));
}
printf("Revenue: NGN %s\n", number_format($revenue / 100, 2));
PHP
php orders.phpCheck it worked
The first command prints NULL, Ready to pack and pending, paid, shipped, cancelled. The script then shows A-1004 as Ready to pack, reports A-1005 skipped: unknown status "refunded", and ends with Revenue: NGN 22,250.00. All four bugs from the first run are fixed. If the shop later adds a refunded status, you add one case, and every match over the enum that does not handle it becomes an error.
Step 6 · Make money and orders readonly value objects
The script still passes loose integers and strings around: nothing stops a caller swapping the quantity and the price, or changing a total after it was worked out. Value objects fix that. A readonly class makes every property readonly: it can be set once, inside the class, and never changed. Constructor property promotion (public int $kobo written in the constructor's parameter list) declares and assigns each property in one place.
Start with Money. Every operation returns a new object instead of changing the old one. That makes one mistake easy: calling $revenue->plus($x); and throwing the result away. PHP 8.5's #[\NoDiscard] attribute turns that into a warning:
cd ~/php-orders-demo
cat > src/Money.php <<'PHP'
<?php
declare(strict_types=1);
final readonly class Money
{
public function __construct(
public int $kobo,
) {
if ($kobo < 0) {
throw new InvalidArgumentException('money cannot be negative');
}
}
#[\NoDiscard]
public function plus(Money $other): Money
{
return new Money($this->kobo + $other->kobo);
}
#[\NoDiscard]
public function times(int $quantity): Money
{
return new Money($this->kobo * $quantity);
}
#[\NoDiscard]
public function percentOff(int $percent): Money
{
return new Money(intdiv($this->kobo * (100 - $percent), 100));
}
public function format(): string
{
return 'NGN ' . number_format($this->kobo / 100, 2);
}
}
PHPThen Order. Its constructor checks the one rule a type cannot express (a quantity of at least 1), and fromCsvLine does all the parsing, using named arguments so each value visibly goes to the right property. byTotalDescending is a comparison function you will use in the next step:
cd ~/php-orders-demo
cat > src/Order.php <<'PHP'
<?php
declare(strict_types=1);
final readonly class Order
{
public function __construct(
public string $id,
public OrderStatus $status,
public string $sku,
public int $quantity,
public Money $unitPrice,
public ?string $coupon = null,
) {
if ($quantity < 1) {
throw new InvalidArgumentException('quantity must be at least 1');
}
}
public static function fromCsvLine(string $line): Order
{
$fields = array_map(trim(...), explode(',', $line));
if (count($fields) !== 6) {
throw new InvalidArgumentException(sprintf('expected 6 fields in "%s"', $line));
}
[$id, $status, $sku, $quantity, $price, $coupon] = $fields;
try {
return new Order(
id: $id,
status: OrderStatus::fromInput($status),
sku: $sku,
quantity: parseWholeNumber($quantity, 'quantity'),
unitPrice: new Money(parseWholeNumber($price, 'unit_price_kobo')),
coupon: parseCoupon($coupon),
);
} catch (InvalidArgumentException $e) {
throw new InvalidArgumentException($id . ': ' . $e->getMessage(), previous: $e);
}
}
public static function byTotalDescending(Order $a, Order $b): int
{
return $b->total()->kobo <=> $a->total()->kobo;
}
public function total(): Money
{
$gross = $this->unitPrice->times($this->quantity);
return $this->coupon === 'SAVE10' ? $gross->percentOff(10) : $gross;
}
}
PHPTry to break a Money from outside, and try to throw away the result of plus:
cd ~/php-orders-demo
cat > poke.php <<'PHP'
<?php
declare(strict_types=1);
require_once __DIR__ . '/src/Money.php';
$price = new Money(150000);
$price->plus(new Money(100));
echo $price->format(), "\n";
try {
$price->kobo = 1;
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
PHP
php poke.phpCheck it worked
You see a warning that starts Warning: The return value of method Money::plus() should either be used or intentionally ignored by casting it as (void), then NGN 1,500.00 (the price did not change, because plus returned a new object that was thrown away), then Error: Cannot modify readonly property Money::$kobo. When you do mean to discard a result, write (void) $price->plus(...) to say so.
Step 7 · Pass functions around with first-class callable syntax
Order::fromCsvLine already uses one: array_map(trim(...), ...). Writing a function or method name followed by (...) creates a Closure from it. The older way was a string such as 'trim' or an array such as [Order::class, 'byTotalDescending']. Those are plain data that happen to name a function, so a typo is only found when the line runs, and editors and analysers cannot reliably follow them. trim(...) is real syntax: PHP checks the name when it builds the closure, and tools treat it as a normal call site you can rename or jump to.
Replace the script with a short one built on the model. It sorts the orders with usort and the byTotalDescending(...) callable, largest first, and adds up revenue with Money:
cd ~/php-orders-demo
rm poke.php
cat > orders.php <<'PHP'
<?php
declare(strict_types=1);
require_once __DIR__ . '/src/parse.php';
require_once __DIR__ . '/src/OrderStatus.php';
require_once __DIR__ . '/src/Money.php';
require_once __DIR__ . '/src/Order.php';
$lines = file(__DIR__ . '/orders.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
throw new RuntimeException('Cannot read orders.csv');
}
$orders = [];
foreach (array_slice($lines, 1) as $line) {
try {
$orders[] = Order::fromCsvLine($line);
} catch (InvalidArgumentException $e) {
printf("skipped %s\n", $e->getMessage());
}
}
usort($orders, Order::byTotalDescending(...));
$revenue = new Money(0);
foreach ($orders as $order) {
printf("%s %-10s %-20s %15s\n", $order->id, $order->sku, $order->status->label(), $order->total()->format());
if ($order->status->countsTowardsRevenue()) {
$revenue = $revenue->plus($order->total());
}
}
printf("Revenue: %s\n", $revenue->format());
PHP
php orders.phpCheck it worked
Two skipped lines come first, each naming the order ID and the reason. Then the orders print largest first: A-1001 at NGN 15,000.00, A-1003 at NGN 4,050.00, A-1004 at NGN 3,200.00. The last line is Revenue: NGN 22,250.00, the same figure as before, now computed with types that cannot hold a negative price, a fractional quantity or an unknown status.
Step 8 · Catch the rest with PHPStan
Types checked at runtime only catch the bugs on the paths your data happens to take. PHPStan reads the code without running it and checks every path. Add a reporting file with two problems that the sample data never triggers. revenueBySku takes and returns a plain array, so nothing says what is inside. couponNote passes a ?string to strtolower, which would throw a TypeError under strict types for any order without a coupon:
cd ~/php-orders-demo
cat > src/report.php <<'PHP'
<?php
declare(strict_types=1);
function revenueBySku(array $orders): array
{
$totals = [];
foreach ($orders as $order) {
$current = $totals[$order->sku] ?? new Money(0);
$totals[$order->sku] = $current->plus($order->total());
}
return $totals;
}
function couponNote(Order $order): string
{
return 'coupon ' . strtolower($order->coupon);
}
PHPInstall PHPStan as a development dependency. Composer creates composer.json and a vendor/ folder:
cd ~/php-orders-demo
composer require --dev "phpstan/phpstan:^2.3"
vendor/bin/phpstan --versionPHPStan has rule levels from 0 (basic checks) to 10 (strictest). Level 6 is a sensible start for code like this: it checks types on calls, returns and properties, and asks for the contents of every array you declare. Write a config file at that level, listing the code to analyse:
cd ~/php-orders-demo
cat > phpstan.neon <<'NEON'
parameters:
level: 6
paths:
- src
- orders.php
NEON
vendor/bin/phpstan analyse --no-progress || echo "phpstan exited with status $?"PHPStan reports two errors in src/report.php: Function revenueBySku() has parameter $orders with no value type specified in iterable type array. and the same for its return type. PHP's own type system has no way to say "a list of Order", so PHPStan reads it from a PHPDoc comment. Add one, and raise the level to 8, which also checks that nullable values are not used as if they were always set:
cd ~/php-orders-demo
cat > src/report.php <<'PHP'
<?php
declare(strict_types=1);
/**
* @param list<Order> $orders
* @return array<string, Money>
*/
function revenueBySku(array $orders): array
{
$totals = [];
foreach ($orders as $order) {
$current = $totals[$order->sku] ?? new Money(0);
$totals[$order->sku] = $current->plus($order->total());
}
return $totals;
}
function couponNote(Order $order): string
{
return 'coupon ' . strtolower($order->coupon);
}
PHP
cat > phpstan.neon <<'NEON'
parameters:
level: 8
paths:
- src
- orders.php
NEON
vendor/bin/phpstan analyse --no-progress || echo "phpstan exited with status $?"The iterable errors are gone, and one new error appears: Parameter #1 $string of function strtolower expects string, string|null given. No order in the CSV ever reached that line, so no run would have shown it. Fix it by saying what a missing coupon means:
cd ~/php-orders-demo
cat > src/report.php <<'PHP'
<?php
declare(strict_types=1);
/**
* @param list<Order> $orders
* @return array<string, Money>
*/
function revenueBySku(array $orders): array
{
$totals = [];
foreach ($orders as $order) {
$current = $totals[$order->sku] ?? new Money(0);
$totals[$order->sku] = $current->plus($order->total());
}
return $totals;
}
function couponNote(Order $order): string
{
return $order->coupon === null ? 'no coupon' : 'coupon ' . strtolower($order->coupon);
}
PHP
vendor/bin/phpstan analyse --no-progressCommit phpstan.neon and composer.json with your code and run vendor/bin/phpstan analyse in CI, so a new nullable slip fails the build instead of reaching a customer. When the codebase is clean at level 8, try levels 9 and 10, which also forbid using mixed values without checking them first.
Check it worked
The first analysis ends with [ERROR] Found 2 errors, the second with [ERROR] Found 1 error, and the last with [OK] No errors. PHPStan exits with status 0 on that last run, which is what a CI job checks.
When you are done, delete the demo folder:
rm -rf ~/php-orders-demoNext steps
You now have a typed domain model: a backed enum for status, readonly value objects for money and orders, parsing at the edge under strict types, and PHPStan at level 8 to guard the code that tests do not reach.
- Replace the
require_oncelines with a Composer autoloader in Manage PHP dependencies and autoloading with Composer. - See what else arrived in the current release in Use the new features in PHP 8.5.
- Compare how another language catches missing values at compile time in Catch null bugs at compile time with C# nullable reference types.
Related tutorials
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
- Write generic functions and types in GoYou will replace three copies of a slice filter with one generic Go 1.27 function, then write constrained helpers, a custom constraint with ~, a generic Set type with an iterator and a generic method, and learn when the standard library or plain code is the better choice.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials