dtz55359 2014-07-17 14:03
浏览 63
已采纳

无法将值存储到类中的变量

I'm trying to store the value from the class below as a variable, so i could used it later on, but I can't get it working.

Any ideas?

class Dates {


    public function __construct($date) {
    $this->DateCompare($date);
    }
    public function DateCompare($date) {
        $date1 = new DateTime("2015-04-08");
        $date2 = new DateTime($date);
        $diff=date_diff($date1,$date2);
        return $diff->format("%a");

    }
}

echo $test = new Dates("2015-05-04");

Error I'm getting: Catchable fatal error: Object of class Dates could not be converted to string in /virtual/index.php

As said before, I don't want to echo that out, just store it in the $test variable, but if I can't even echo that out, then I'm not storing it either.

  • 写回答

2条回答 默认 最新

  • dpgbh20688 2014-07-17 14:06
    关注

    The only thing a class constructor can return [directly or indirectly] is itself.

    public static function instance() { return new self(); }
    

    Add the above line and then get rid of the constructor. Replace the echo call with:

    $test = Dates::instance() -> DateCompare("2015-05-04");
    
    echo $test;
    

    Explanation: your initial code, was trying to echo an instance of the Dates Object, the return you had was ignored because a new Class ALWAYS HAS TO Return ITSELF Actually the return you had got dumped, since it was returned back to the constructor but didn't go anywhere from there.

    An alternative, if you were planning to Echo it; would be to add a __tostring() function which would get triggered when you try to echo the Class Instance Object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算