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 void or callable property 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

← All PHP 7 questions