Content · Web Development · PHP

PHP Strict Types with declare(strict_types=1)

Strict types changes how scalar type coercion is performed at the call site. The directive is file-scoped; it does not validate external user input for.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

Strict types changes how scalar type coercion is performed at the call site.

What It Does


Strict types changes how scalar type coercion is performed at the call site. The following examples distinguish a normal use case, a boundary case and a practical application.

Requirements and Compatibility


PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.

The strict_types declaration applies in the calling file for scalar parameter typing; it does not perform business validation or replace explicit input parsing.

The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.

Example 1: Basic Behavior


Start with the smallest meaningful working case.

<?php
declare(strict_types=1);
function units(int $count): int { return $count * 2; }
try { units('3'); } catch (TypeError $e) { echo 'Rejected string at strict call site'; }

Example 2: Another Case


Examine the edge case and the observable result.

<?php
declare(strict_types=1);
function subtotal(float $price): float { return $price * 2; }
echo subtotal(5); // An int can be accepted for float

Practical Example: Putting It to Use


Apply the technique to a small practical task.

<?php
declare(strict_types=1);
function fullName(string $first, string $last): string { return $first . ' ' . $last; }
echo fullName('Mira', 'Chen');

Important Behavior and Edge Cases


The directive is file-scoped; it does not validate external user input for you.

Comparison with Related Functions or Approaches


OptionWhat it means in practice
Strict Types with declare(strict_types=1)Strict types changes how scalar type coercion is performed at the call site.
Related approachA scalar int can still be accepted where float is declared.

Common Beginner Mistakes


MistakeCorrect approach
Ignoring the important boundary for Strict Types with declare(strict_types=1)The directive is file-scoped; it does not validate external user input for you.
Assuming a related mechanism has the same behaviorA scalar int can still be accepted where float is declared.

Key Takeaways


  • Strict types changes how scalar type coercion is performed at the call site.
  • The directive is file-scoped; it does not validate external user input for you.
  • A scalar int can still be accepted where float is declared.

Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.

Share this resourceSend this page to someone who may find it useful.