Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

DateTimeInterface

DateTimeInterface is a PHP interface implemented by both DateTime and DateTimeImmutable. It defines the common API shared by both mutable and immutable date-time objects.

Using DateTimeInterface as a type in function signatures accepts either class, making code agnostic to mutability. It cannot be implemented by user-defined classes directly; it exists solely to type both built-in date-time classes.

DateTimeInterface exposes methods such as format(), getTimestamp(), getTimezone(), and diff().

<?php

    function formatDate(DateTimeInterface $date): string {
        return $date->format('Y-m-d');
    }
    
    // both classes satisfy the type
    echo formatDate(new DateTime('2024-01-15'));
    echo formatDate(new DateTimeImmutable('2024-06-03'));

?>

Documentation

See Also