PHP 7 interview question · Most asked

Explain scalar type declarations and coercive vs strict mode in PHP 7.

Summary

PHP 7 allows int, float, string and bool parameter types. By default (coercive mode) compatible values are converted, e.g. '5' → 5; with declare(strict_types=1) mismatches throw TypeError.

Longer Answer

In coercive mode, function add(int $a) called with '5' works, and with '5 apples' emits a notice in 7.x. With strict types, only an exact type match is accepted, except that an int may be passed to a float parameter.

Strict mode is decided by the calling file, which lets libraries adopt types without breaking callers.

Code Example

<?php
declare(strict_types=1);

function add(int $a, int $b): int
{
    return $a + $b;
}

add(1, 2);     // 3
add('1', 2);   // TypeError in strict mode

Key Points

  • Types: int, float, string, bool
  • Coercive by default
  • strict_types=1 per file, caller-decided
  • Only int → float widening allowed in strict mode

More most-asked PHP 7 questions

← All PHP 7 questions