PHP

Lesson 01

Strict types and return types

Make PHP function contracts explicit with strict scalar types and return types so reviewers can catch coercion bugs at boundaries.

Good Code

src/Billing/InvoiceTotal.php
<?php declare(strict_types=1);

function invoiceTotalCents(int $subtotalCents, int $taxCents): int
{
    if ($subtotalCents < 0 || $taxCents < 0) {
        throw new InvalidArgumentException('Invoice amounts must be positive.');
    }

    return $subtotalCents + $taxCents;
}

Bad Code

invoice.php
<?php

function invoiceTotal($subtotal, $tax)
{
    return $subtotal + $tax;
}

echo invoiceTotal($_POST['subtotal'], $_POST['tax']);

Review Notes

What to review

Good Code

The good version declares strict typing, names the unit of money, returns a specific type, and rejects invalid values before computing.

Bad Code

The bad version relies on PHP coercion and untyped request values. A reviewer has to infer whether strings, floats, negative numbers, or missing fields are valid.

Takeaways

  • A PHP file that handles business rules should make parameter and return expectations visible at the function boundary.