DateTime::__serialize
DateTimeImmutable::__serialize
DateTimeInterface::__serialize
(PHP 8 >= 8.2.0)
DateTime::__serialize -- DateTimeImmutable::__serialize -- DateTimeInterface::__serialize — Serialize a DateTime
说明
The __serialize() handler.
参数
此函数没有参数。
返回值
The serialized representation of the DateTime object.
示例
示例 #1 DateTime::__serialize() example
<?php
class CustomDateTimeImmutable extends DateTimeImmutable
{
#[\Override]
public function __serialize(): array
{
return [
'date' => $this->format(DateTimeInterface::W3C),
'timestamp' => $this->getTimestamp(),
'timezone' => $this->getTimeZone()->getName(),
'to' => 'Drink a cup of coffee',
];
}
}
$date = new CustomDateTimeImmutable('2025-03-27');
var_dump(serialize($date));以上示例会输出:
string(171) "O:23:"CustomDateTimeImmutable":4:{s:4:"date";s:25:"2025-03-27T00:00:00+00:00";s:9:"timestamp";i:1743033600;s:8:"timezone";s:3:"UTC";s:2:"to";s:21:"Drink a cup of coffee";}"
注释
警告
An Error is thrown when attempting to unserialize a custom DateTime object if __serialize() is defined but __unserialize() is missing.
参见
- DateTime::__unserialize() - Unserialize an Datetime
来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。
