PHP 7 interview question · Most asked
What are typed properties in PHP 7.4?
Summary
PHP 7.4 lets class properties declare types (public int $id;), enforced on every write; an uninitialized typed property throws an Error when read.
Longer Answer
Typed properties start in an uninitialized state rather than null, unless given a default. Reading before assignment throws "must not be accessed before initialization". Nullable types need an explicit = null default if you want null initially. All types except void and callable are supported, and strict_types affects writes like parameters.
Code Example
<?php
class User
{
public int $id;
public string $email;
public ?DateTimeImmutable $verifiedAt = null;
public array $roles = [];
}
$u = new User();
echo $u->email; // Error: must not be accessed before initialization
Key Points
private ?string $name = null;- Uninitialized ≠ null
- No
voidorcallableproperty types - Writes are type-checked
Explanation
Common mistakes
- Assuming typed properties default to null
- Using
isset()vs uninitialized semantics incorrectly
More most-asked PHP 7 questions
- What are arrow functions in PHP 7.4 and how do they differ from closures?
- How do return type declarations work in PHP 7?
- What were the headline improvements of PHP 7.0 over PHP 5.6?
- Explain scalar type declarations and coercive vs strict mode in PHP 7.
- 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?
- What are the main breaking changes when upgrading from PHP 7.4 to 8.0?