2018-08-02 21:33
浏览 463

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.

图片转代码服务由CSDN问答提供 功能建议


在这里,我只是想在这个变量上添加一天(在其他地方显示给用户)每次通过我设置的按钮执行此功能时,该按钮会路由到某个 地点。 但是,我不断收到此错误


每当我尝试执行此操作。 我是新手使用Carbon界面并浏览文档,这导致我尝试解析函数(当我遇到与字符串相同的错误时工作)但显然无济于事。 感谢任何帮助和/或可能解释此错误如何工作。

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

提前致谢。 如果有更好的方法(通过按钮/链接逐步添加天数),我很乐意听到它。 在整天处理应用程序后,我的逻辑似乎有缺陷。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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');
    解决 无用
    打赏 举报

相关推荐 更多相似问题