Introduction
When working with dates in PHP, the Carbon library is extremely convenient.
Sometimes, you may need to convert a mutable Carbon instance into an immutable CarbonImmutable instance to ensure the date object cannot be modified after creation.
In this article, we’ll explain the difference between Carbon and CarbonImmutable and how to easily convert between them.
Difference Between Carbon and CarbonImmutable
- Carbon Mutable date object – allows changes to the same instance. Example:
$date = Carbon::now();
$date->addDay(); // modifies the original object
- CarbonImmutable
- Immutable date object – any change returns a new instance without altering the original. Example:
$date = CarbonImmutable::now();
$newDate = $date->addDay(); // original $date remains unchanged
Converting from Carbon to CarbonImmutable
If you already have a Carbon instance and want to make it immutable, you can use the toImmutable() method.
Example:
use Carbon\Carbon;
$carbon = Carbon::now();
$immutable = $carbon->toImmutable();
echo get_class($carbon); // Carbon\Carbon
echo get_class($immutable); // Carbon\CarbonImmutable
Converting from CarbonImmutable to Carbon
If you have an immutable instance but want to make it mutable again, use toMutable().
Example:
use Carbon\CarbonImmutable;
$immutable = CarbonImmutable::now();
$mutable = $immutable->toMutable();
echo get_class($immutable); // Carbon\CarbonImmutable
echo get_class($mutable); // Carbon\Carbon
When to Use Immutable Dates
You might prefer CarbonImmutable in situations such as:
- Working with date history or logs (to avoid accidental changes).
- Writing pure functions where input data should not change.
- Enforcing strict immutability in your application’s domain layer.
Summary
- Carbon = mutable, CarbonImmutable = immutable.
- Convert with:
- $carbon->toImmutable() → Carbon to CarbonImmutable
- $immutable->toMutable() → CarbonImmutable to Carbon
- Use immutable dates to avoid unintentional modifications.
By understanding and applying these conversions, you can write safer and more predictable date-handling code in PHP.
コメント