[PHP] CarbonインスタンスをCarbonImmutableに変換する方法

PHP PHP
Mainly articles about PHP

はじめに

PHPで日付を扱う際、Carbonライブラリは非常に便利です。

しかし、場合によっては、変更可能な Carbon インスタンスを変更不可能な CarbonImmutable インスタンスに変換して、作成後に日付オブジェクトが変更されないようにしたいことがあります。

この記事では、Carbon と CarbonImmutable の違い、および変換方法について解説します。


Carbon と CarbonImmutable の違い

  • Carbon 変更可能(mutable)な日付オブジェクト。 同じインスタンスを直接変更できます。
$date = Carbon::now();
$date->addDay(); // 元のオブジェクトが変更される
  • CarbonImmutable
    • 変更不可能(immutable)な日付オブジェクト。 変更操作は新しいインスタンスを返し、元のオブジェクトは変わりません。
$date = CarbonImmutable::now();
$newDate = $date->addDay(); // 元の$dateはそのまま

Carbon から CarbonImmutable への変換

すでに Carbon インスタンスを持っていて、それを変更不可能にしたい場合は、toImmutable() メソッドを使います。

例:

use Carbon\Carbon;

$carbon = Carbon::now();
$immutable = $carbon->toImmutable();

echo get_class($carbon);     // Carbon\Carbon
echo get_class($immutable);  // Carbon\CarbonImmutable

CarbonImmutable から Carbon への変換

変更不可能なインスタンスを、再び変更可能にしたい場合は、toMutable() メソッドを使います。

例:

use Carbon\CarbonImmutable;

$immutable = CarbonImmutable::now();
$mutable = $immutable->toMutable();

echo get_class($immutable); // Carbon\CarbonImmutable
echo get_class($mutable);   // Carbon\Carbon

Immutable な日付を使うべきケース

CarbonImmutable の使用が適しているのは以下のような場面です:

  • 履歴やログなど、後から変更されてはいけないデータを扱う場合
  • 入力値を変えない純粋関数(pure function)を書く場合
  • アプリケーションのドメイン層で厳格な不変性を求める場合

まとめ

  • Carbon = 変更可能、CarbonImmutable = 変更不可能
  • 変換方法:
    • $carbon->toImmutable() → Carbon → CarbonImmutable
    • $immutable->toMutable() → CarbonImmutable → Carbon
  • Immutable は意図しない変更を防ぐために有効

この変換を理解して使い分ければ、より安全で予測可能な日付処理が可能になります。

コメント

タイトルとURLをコピーしました