douxing6434 2018-08-02 21:33
浏览 526
已采纳

Laravel中的Carbon - 在整数上调用成员函数addDay()

I'm trying to build a scheduler in which an incremental day addition and subtraction method is required.

Here, I am simply trying to add a day to this variable (which is displayed to the user elsewhere) each time this function is executed via a button I set up that routes to a certain location. But, I keep getting this error

Call to a member function addDay() on integer

whenever I try to execute this. I am new to using the Carbon interface and looked through the documents, which led me to try parsing the function (worked when I had the same error with a string) but to no avail obviously. Any help is appreciated and/or a possible explanation of how this error is working really.

function addDay(){
$day = (int) Carbon::now()->format('j');
$day = $day->addDay();
}

Thanks in advance. If there is a better way to do this (adding days incrementally with the button/link), I would love to hear it. My logic seems flawed after working on the application the entire day.

  • 写回答

4条回答 默认 最新

  • dongyu2047 2018-08-02 22:12
    关注

    You're casting the Carbon date object into an integer by using the (int) in the first $day variable. Therefor when you're trying to access the function addDay() it's failing, because $day is no longer a Carbon object but an integer.

    $day = Carbon::now();
    $day = $day->addDay()->format('j');
    

    This should work, and if you need to cast it to an integer for some reason, then do it like this.

    $day = Carbon::now();
    $day = (int) $day->addDay()->format('j');
    

    This way you cast the integer after you've added the day.

    There is also a much cleaner approach to this syntax, which uses method chaining like so

    $day = (int) Carbon::now()->addDay()->format('j');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容