Skip to content

Instantly share code, notes, and snippets.

@jakewtaylor
Created March 6, 2019 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakewtaylor/215aa388cac3063b07ba6183f8114c52 to your computer and use it in GitHub Desktop.
Save jakewtaylor/215aa388cac3063b07ba6183f8114c52 to your computer and use it in GitHub Desktop.
Carbon 2.0 Immutable demonstration
<?php
$mutable = Carbon::now();
$immutable = CarbonImmutable::now();
$modifiedMutable = $mutable->add(1, 'day');
$modifiedImmutable = CarbonImmutable::now()->add(1, 'day');
var_dump($modifiedMutable === $mutable); // bool(true)
var_dump($mutable->isoFormat('dddd D')); // string(8) "Sunday 3"
var_dump($modifiedMutable->isoFormat('dddd D')); // string(8) "Sunday 3"
// So it means $mutable and $modifiedMutable are the same object
// both set to now + 1 day.
var_dump($modifiedImmutable === $immutable); // bool(false)
var_dump($immutable->isoFormat('dddd D')); // string(10) "Saturday 2"
var_dump($modifiedImmutable->isoFormat('dddd D')); // string(8) "Sunday 3"
// While $immutable is still set to now and cannot be changed and
// $modifiedImmutable is a new instance created from $immutable
// set to now + 1 day.
$mutable = CarbonImmutable::now()->toMutable();
var_dump($mutable->isMutable()); // bool(true)
var_dump($mutable->isImmutable()); // bool(false)
$immutable = Carbon::now()->toImmutable();
var_dump($immutable->isMutable()); // bool(false)
var_dump($immutable->isImmutable()); // bool(true)
@malitta
Copy link

malitta commented Jul 27, 2021

Nice one! I think line 6 should be $immutable->add(... though

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment