PHP · Intermediate

Declare strict types in a PHP file

Make scalar parameter and return values reject unintended type coercion within this PHP file.

Share Email

Place declare(strict_types=1); at the top of a PHP file, immediately after the opening tag. Calls made from a strict file then require compatible scalar arguments rather than silently coercing many values.

<?php
declare(strict_types=1);

function calculateTotal(int $quantity, float $unitPrice): float
{
    return $quantity * $unitPrice;
}

Strict mode applies to calls made from the file where it is enabled; it does not automatically change every file in an application.

Review commands and snippets before using them in your environment. Examples are not executed by LeafDeft.