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=1per file, caller-decided- Only int → float widening allowed in strict mode
More most-asked PHP 7 questions
- What are typed properties in PHP 7.4?
- What are arrow functions in PHP 7.4 and how do they differ from closures?
- What were the headline improvements of PHP 7.0 over PHP 5.6?
- Explain the `Throwable`, `Error` and `Exception` hierarchy introduced in PHP 7.
- What are nullable types in PHP 7.1?
- What does the null coalescing operator `??` do, and how is it different from `isset()` with a ternary?
- How do return type declarations work in PHP 7?
- What are the main breaking changes when upgrading from PHP 7.4 to 8.0?