Skip to content

Custom properties of DateTimeImmutable child classes are not serialized #10152

Closed

Description

@derrabus

Description

The following code:

<?php

class MyDateTimeImmutable extends DateTimeImmutable {
    public function __construct(
        string $datetime = "now",
        ?DateTimeZone $timezone = null,
        public ?bool $myProperty = null,
    ) {
        parent::__construct($datetime, $timezone);
    }
}

$datetime = new MyDateTimeImmutable('2022-12-22T11:26:00Z', myProperty: true);
$serialized = serialize($datetime);
$unserialized = unserialize($serialized);

var_dump($unserialized->myProperty);

Resulted in this output:

Fatal error: Uncaught Error: Typed property MyDateTimeImmutable::$myProperty must not be accessed before initialization in /path/to/file.php:17
Stack trace:
#0 {main}
  thrown in /path/to/file.php on line 17

But I expected this output instead:

bool(true)

The propblem can be observed here: https://3v4l.org/8q4Or

Apparently, MyDateTimeImmutable::$myProperty is not included in the serialized string anymore on PHP 8.2.0. On PHP 8.0/8.1, it does appear there and is unserialized properly.

PHP Version

PHP 8.2.0

Operating System

No response

Activity

  1. cmb69 commented on Dec 22, 2022

    @cmb69
    Member

    This is because DateTime(Immutable) (and DateTimeZone) now implement ::__(un)serialize() (#8422). Besides this is not documented, it looks like subclasses have been overlooked. Or is that deliberate, @derickr?

  2. derickr commented on Dec 23, 2022

    @derickr
    Member

    This is not deliberate, and hence a bug.

  3. OskarStark commented on Jan 31, 2023

    @OskarStark
    Contributor

    Thank you very much @derickr 🎉 ☀️

  4. OskarStark commented on Feb 22, 2023

    @OskarStark
    Contributor

    Was this released in 8.2.3, because I cannot find anything in the changelog

    cc @mvhirsch

  5. TimWolla commented on Feb 22, 2023

    @TimWolla
    Member

    8.2.3 was an irregular release that was coordinated with other projects. It only contains the security fixes. The fix is included in the changelog for 8.2.4:

    php-src/NEWS

    Lines 22 to 23 in 8c87a5c

    . Fix GH-10152 (Custom properties of Date's child classes are not
    serialised). (Derick)

  6. OskarStark commented on Feb 22, 2023

    @OskarStark
    Contributor

    Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions