Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

The type system

For a long time PHP was a language without types: anything could be passed to a function. Today types are given for parameters, results and properties. A bug that used to surface a week later in front of a user is now caught at the moment of the call.

Parameter and return types

<?php
 
function repeat(string $text, int $times): string
{
    return str_repeat($text, $times);
}
 
echo repeat('ab', 3); // ababab

If a value of the wrong type is passed, PHP throws a TypeError.

Strict mode

By default PHP tries to convert a value: the string '5' becomes a number. The strict_types directive forbids that. It is written as the first line of a file:

<?php
 
declare(strict_types=1);
 
function double(int $number): int
{
    return $number * 2;
}
 
try {
    echo double('5');
} catch (TypeError $error) {
    echo 'An integer is required';
}

Without the directive the function would silently return 10. New projects turn strict mode on in every file.

A value or null

A question mark before the type allows null:

<?php
 
function findUser(int $id): ?string
{
    return $id === 1 ? 'Anna' : null;
}
 
echo findUser(1) ?? 'not found', "\n"; // Anna
echo findUser(2) ?? 'not found';       // not found

Union types

A vertical bar lists the allowed types:

<?php
 
function formatId(int|string $id): string
{
    return is_int($id) ? '#' . $id : strtoupper($id);
}
 
echo formatId(7), ' ', formatId('ab-1'); // #7 AB-1

?string is the same as string|null.

void and never

void means a function returns nothing. never means it does not return at all: it always throws an exception or ends the program:

<?php
 
function logMessage(string $message): void
{
    echo '[log] ', $message, "\n";
}
 
function fail(string $message): never
{
    throw new RuntimeException($message);
}
 
logMessage('Start');
 
try {
    fail('Stop');
} catch (RuntimeException $error) {
    echo $error->getMessage(); // Stop
}

Typed properties

Class properties have types too. A value of another type cannot be assigned:

<?php
 
class Product
{
    public function __construct(
        public string $title,
        public int $price,
        public ?string $description = null,
    ) {}
}
 
$product = new Product('Tea', 250);
 
echo $product->title, ' ', $product->price, ' ', $product->description ?? 'no description';

The main types

TypeValues
int, float, string, boolSimple values
arrayAn array
callableA function
iterableAn array or an object that can be looped over
mixedAny value
self, staticThe current class
A class or interface nameAn object of that type

Common mistake

The array type says nothing about what the array holds. A function expecting a list of numbers accepts an array of strings too. Check the contents yourself or describe them in a comment above the function — editors take such hints into account:

<?php
 
/**
 * @param int[] $numbers
 */
function total(array $numbers): int
{
    return array_sum($numbers);
}
 
echo total([1, 2, 3]); // 6

Thanks for reading!

Donate to the site — we work hard for you.