Cannot serialize IntlTimeZone objects
Description
The following code:
<?php
$tz = IntlTimeZone::createTimeZone('Europe/Amsterdam');
$tz = unserialize(serialize($tz));
var_export($tz->getId());
Resulted in this output:
false
But I expected this output instead:
'Europe/Amsterdam'
It looks like the implementation of __serialize is broken, as the string doesn't contain any object data:
echo serialize(IntlTimeZone::createTimeZone('Europe/Amsterdam'));
// outputs O:12:"IntlTimeZone":0:{}
PHP Version
PHP 7.4.27 (cli) (built: Dec 21 2021 21:31:45) ( NTS )
Operating System
No response
It doesn't look like IntlTimeZone supports serialization.
https://3v4l.org/jnXqP#v8.1.1
$tz = IntlTimeZone::createTimeZone('Europe/Amsterdam');
var_dump(serialize($tz));
string(24) "O:12:"IntlTimeZone":0:{}"
But we could throw an error or at least emit some warning.
Would it be difficult to implement serialization? Or do you worry about backwards compatibility?
@drjayvee I know nothing about intl so I'm not sure. Compatibility shouldn't be a concern.
Would it be difficult to implement serialization?
I don't think it would be difficult, but what is the use case? I assume that IntlTimezone is most often used with IntlCalendar and IntlDateFormatter, but neither of these properly supports (un)serialization. Other classes of the intl extension might exhibit the same behavior.
I was under the admittedly naive assumption that every class supports serialization, unless it's especially tricky.
Our particular use case is:
class LocaleConfiguration {
public IntlTimeZone $timeZone = null;
public string $locale = 'en-US';
public int $firstWeekDay = 1;
// etc
}
And then cache the user's configuration in their session, memory cache, or elsewhere.
The simple yet awkward workaround is
public function __serialize(): array {
return [
'timeZone' => $this->timeZone->getID(),
'locale' => $this->locale,
'firstWeekDay' => $this->firstWeekDay,
// etc
];
}
// reverse for __unserialize()
Okay, for this case being able to (un)serialize IntlTimeZone objects would make sense.
Note, though, that a lot of internal classes don't support (un)serialization.
Serialization of these objects will be disallowed as of PHP 8.2.0. PRs to properly support (un)serialization (of individual classes) are welcome!