Skip to content

Chapter 35 of 38

Type Declarations

Use scalar, nullable, union, intersection, mixed, never, and return types.

36 minutes 10 quick checksBy Subha Prasad
Lesson 35 of 38Course navigation

Lesson content

Read, practise, then check your understanding

Modern PHP supports scalar/class parameter and return types, nullable types, unions, intersections, mixed, void, never, static, self, and parent.

Practical example

<?php
declare(strict_types=1);
function find(int $id): User|null { return $repository->find($id); }
function normalize(int|string $value): string { return (string) $value; }
function fail(string $message): never { throw new RuntimeException($message); }

Strict types improves scalar call checks but does not replace validation. Choose types that express domain states, avoid broad mixed when a smaller union works, and use static analysis/docblock generics for collection element contracts PHP cannot fully express natively.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes scalar type declaration?
Which PHP term matches this description: A parameter or return constraint such as int or string.
Which statement best describes union type?
Which PHP term matches this description: A declaration allowing one of multiple named types.
Which statement best describes nullable type?
Which PHP term matches this description: A declaration allowing a type or null.
Which statement best describes mixed?
Which PHP term matches this description: The top type allowing any value.
Which statement best describes never?
Which PHP term matches this description: A return type indicating the function never returns normally.

0 of 10 checks passed

Your progress is saved on this device.