The PHP Carbon class changes the original value of my variable

I am trying to make a few navigation buttons in the form of a calendar that I create, and I use carbon to create dates.

This is the code in the controller:

if ($date == null) {
    $date = \Carbon\Carbon::now();
} else {
    $date = \Carbon\Carbon::createFromFormat('Y-m-d', $date);
}
$navDays = [
    '-7Days' => $date->subDay('7')->toDateString(),
    '-1Day'  => $date->subDay('1')->toDateString(),
    'Today'    => $date->today()->toDateString(),
    '+1Day'  => $date->addDay('1')->toDateString(),
    '+7Days' => $date->addDay('7')->toDateString()
];

and then I, in my opinion, I do this:

@foreach($navDays as $key => $i)
    <li>
        <a href="/planner/bookings/{{ $i }}" class="small button">
            {{ $key }}
        </a>
    </li>
@endforeach

This problem is that carbon seems to change $ date during array creation, because these are the dates I get (with $dateset to 2015-11-29):

<ul class="button-group even-5">
    <li><a href="/planner/bookings/2015-11-22" class="small button">-7Days</a></li>
    <li><a href="/planner/bookings/2015-11-21" class="small button">-1Day</a></li>
    <li><a href="/planner/bookings/2015-12-22" class="small button">Today</a></li>
    <li><a href="/planner/bookings/2015-11-22" class="small button">+1Day</a></li>
    <li><a href="/planner/bookings/2015-11-29" class="small button">+7Days</a></li>
</ul>

Does anyone know what I'm doing wrong?

+17
source share
3 answers

When you run these methods on a Carbon object, it updates the object itself. Therefore, it addDay()moves the Carbon value one day ahead.

Here is what you need to do:

$now = Carbon::now();

$now->copy()->addDay();
$now->copy()->addMonth();
$now->copy()->addYear();
// etc...

copy Carbon, , $now.

, , Carbon:

  • copy
  • clone - copy

: https://carbon.nesbot.com/docs/

+33

, , subDay()/addDay() , ... DateTime object modify():

DateTime:: modify - date_modify -

( )

$navDays = [
    '-7Days' => (clone $date)->subDay('7')->toDateString(),
    '-1Day'  => (clone $date)->subDay('1')->toDateString(),
    'Today'  => (clone $date)->today()->toDateString(),
    '+1Day'  => (clone $date)->addDay('1')->toDateString(),
    '+7Days' => (clone $date)->addDay('7')->toDateString()
];
+10

() Carbon. , , .

$dt = Carbon::now();
echo $dt->diffInYears($dt->copy()->addYear());  // 1

// $dt was unchanged and still holds the value of Carbon:now()
0

Source: https://habr.com/ru/post/1621260/


All Articles