未分配变量的碳分配

时间:2017-04-30 06:02:06

标签: php laravel php-carbon

我在视图中设置了两个日期选择器;一个用于开始日期,一个用于结束日期。 请求将传递给控制器​​索引方法,在该方法中,它与此if块进行交互。

如果我设置了开始日期,例如1st of April,我希望:

  • $start_date == 2017-04-01 00:00:00
  • $end_date == 2017-04-08 00:00:00(一周之后)

但是当我在阻止后运行dd($start_time.' '.$end_time)时,它会返回

  • 2017-04-08 00:00:00 2017-04-08 00:00:00
    // If start or end date is not passed, set the bookings to view the upcoming week
    if (isset($request->start_date) && isset($request->end_date))
    {
        $start_date = Carbon::parse($request->start_date);
        $end_date = Carbon::parse($request->end_date);
        if ($start_date->diffInDays($end_date, false) < 1 )
        {
            return redirect()->route('bookings.index')->with('errors', 'Please choose an end date <strong>after</strong> start date!');
        }

    }
    else if (isset($request->start_date))
    {
        $start_date = Carbon::parse($request->start_date);
        $end_date = $start_date->addWeek();
    }
    else if (isset($request->end_date))
    {
        $end_date = Carbon::parse($request->end_date);
        $start_date = ($end_date->subWeek());
    }
    else
    {
        $start_date = Carbon::now();
        $end_date = Carbon::now()->addweek();
    }

这可能会发生什么?

1 个答案:

答案 0 :(得分:1)

代码中出现问题是因为 Carbon对象是可变的

这基本上意味着当您$end_date = $start_date->addWeek();时,start_dateend_date都是相同的对象。

所以你可以clone start_dateend_date,然后再调用方法。

解决方案应为

   // If start or end date is not passed, set the bookings to view the upcoming week
    if (isset($request->start_date) && isset($request->end_date))
    {
        $start_date = Carbon::parse($request->start_date);
        $end_date = Carbon::parse($request->end_date);
        if ($start_date->diffInDays($end_date, false) < 1 )
        {
            return redirect()->route('bookings.index')->with('errors', 'Please choose an end date <strong>after</strong> start date!');
        }

    }
    else if (isset($request->start_date))
    {
        $start_date = Carbon::parse($request->start_date);
        $end_date = clone $start_date;
        $end_date = $end_date->addWeek();
    }
    else if (isset($request->end_date))
    {
        $end_date = Carbon::parse($request->end_date);
        $start_date= clone $end_date;
        $start_date= $start_date->subWeek();
    }
    else
    {
        $start_date = Carbon::now();
        $end_date = Carbon::now()->addweek();
    }