Kaedah createFromImmutable Kelas DateTime

Kaedah statik createFromImmutable kelas DateTime mencipta objek boleh ubah DateTime baharu berdasarkan objek tidak berubah DateTimeImmutable.

Sintaks

phpDateTime::createFromImmutable(DateTimeImmutable $object): DateTime

Contoh

Mari cipta objek boleh ubah DateTime daripada objek tidak berubah:

php<?php
  $immutable = new DateTimeImmutable('2023-07-15');
  $mutable = DateTime::createFromImmutable($immutable);
  echo $mutable->format('Y-m-d');
?>

Keputusan pelaksanaan kod:

php'2023-07-15'

Contoh

Mari tunjukkan perbezaan antara objek boleh ubah dan tidak berubah:

php<?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');
?>

Keputusan pelaksanaan kod:

php'2023-07-16'
'2023-07-16'

Contoh

Penciptaan objek boleh ubah dengan zon waktu:

php<?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');
?>

Keputusan pelaksanaan kod:

php'2023-07-15 14:30:00 Europe/Moscow'

Lihat juga