Bug #65151 [Opn->Nab]: DateTime subclasses cant use custom serializer
| From: | cmb@php.net | Date: | Mon, 20 Apr 2020 15:21:53 +0000 |
| Subject: | Bug #65151 [Opn->Nab]: DateTime subclasses cant use custom serializer | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-226693@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=65151&edit=1
ID: 65151
Updated by: cmb@php.net
Reported by: mike at silverorange dot com
Summary: DateTime subclasses cant use custom serializer
-Status: Open
+Status: Not a bug
Type: Bug
Package: Date/time related
Operating System: CentOS or RHEL
PHP Version: 5.3.26
-Assigned To:
+Assigned To: cmb
Block user comment: N
Private report: N
New Comment:
Indeed, it is like Seth has explained.
Previous Comments:
------------------------------------------------------------------------
[2014-01-18 05:23:13] seth dot johnson+phpnet at gmail dot com
This is not a bug.
An unserialize implementation is responsible for properly constructing the entire object and that
includes calling its parent's constructor if that would normally be necessary. You would have
the same problem if you overrode DateTime's constructor and did not call parent::__construct.
It's fairly easy to address in code though. Just call the parent's constructor in
unserialize, e.g.
public function unserialize($data)
{
parent::__construct(null);
$data = unserialize($data);
$this->setTimestamp($data[0]);
$this->setTimezone(new DateTimeZone($data[1]));
}
------------------------------------------------------------------------
[2013-06-27 21:18:47] mike at silverorange dot com
Description:
------------
If a DateTime subclass implements Serializable it cant be unserialized. A PHP
warning is raised when restoring the time zone is attempted.
Test script:
---------------
class MyDate extends DateTime implements Serializable
{
public function serialize()
{
$data = array(
$this->getTimestamp(),
$this->dateTimezone()->getName()
);
return serialize($data);
}
public function unserialize($data)
{
$data = unserialize($data);
$this->setTimestamp($data[0]);
$this->setTimezone(new DateTimeZone($data[1]));
}
}
$d = new MyDate('2013-01-01', new DateTimeZone('UTC'));
echo unserialize(serialize($d))->format('c');
Expected result:
----------------
2013-01-01T00:00:00+00:00
Actual result:
--------------
Warning: DateTime::setTimezone(): The DateTime object has not been correctly
initialized by its constructor
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=65151&edit=1