วิธี createFromImmutable ของคลาส DateTime
วิธีแบบสถิติ createFromImmutable ของคลาส DateTime สร้างวัตถุ DateTime ที่สามารถเปลี่ยนแปลงได้ใหม่บนพื้นฐานของวัตถุ DateTimeImmutable ที่ไม่สามารถเปลี่ยนแปลงได้
ไวยากรณ์
DateTime::createFromImmutable(DateTimeImmutable $object): DateTime
ตัวอย่าง
สร้างวัตถุ DateTime ที่สามารถเปลี่ยนแปลงได้จากวัตถุที่ไม่สามารถเปลี่ยนแปลงได้:
<?php
$immutable = new DateTimeImmutable('2023-07-15');
$mutable = DateTime::createFromImmutable($immutable);
echo $mutable->format('Y-m-d');
?>
ผลลัพธ์ของการดำเนินการโค้ด:
'2023-07-15'
ตัวอย่าง
สาธิตความแตกต่างระหว่างวัตถุที่สามารถเปลี่ยนแปลงได้และวัตถุที่ไม่สามารถเปลี่ยนแปลงได้:
<?php
$immutable = new DateTimeImmutable('2023-07-15');
$mutable = DateTime::createFromImmutable($immutable);
$mutable->modify('+1 day');
$newImmutable = $immutable->modify('+1 day');
echo $mutable->format('Y-m-d') . "\n";
echo $newImmutable->format('Y-m-d');
?>
ผลลัพธ์ของการดำเนินการโค้ด:
'2023-07-16'
'2023-07-16'
ตัวอย่าง
การสร้างวัตถุที่สามารถเปลี่ยนแปลงได้พร้อมโซนเวลา:
<?php
$timezone = new DateTimeZone('Europe/Moscow');
$immutable = new DateTimeImmutable('now', $timezone);
$mutable = DateTime::createFromImmutable($immutable);
echo $mutable->format('Y-m-d H:i:s e');
?>
ผลลัพธ์ของการดำเนินการโค้ด:
'2023-07-15 14:30:00 Europe/Moscow'
ดูเพิ่มเติม
-
คลาส
DateTimeImmutable,
ซึ่งแสดงถึงวันที่และเวลาที่ไม่สามารถเปลี่ยนแปลงได้