dtmu88600 2013-05-02 11:46
浏览 105
已采纳

在PHP中添加Object和整数的语义?

class wat
{
   public $a = 3.14;
   public $x = 9;
   public $y = 2;
}


$a = new wat();

var_dump(1000 + $a);
var_dump($a + 1000);

The output is:

int(1001)
int(1001)

Well, adding the wat* object to an integer is obviously not the right thing to do, since PHP complains about it with "Object of class wat could not be converted to int", but still, what does it do?

(I also have a practical reason for asking this, I want to refactor a function to get rid of the "PHP Notice", while still keeping behaviour completely unchanged.)


*: http://img.youtube.com/vi/kXEgk1Hdze0/1.jpg
  • 写回答

3条回答 默认 最新

  • douyin2962 2013-05-02 12:01
    关注

    Addition (+) implicitly casts both operands to float if either one of them is float, otherwise both operands are cast to int (See paragraph #2.)

    It seems that, at least for now, an object cast to int results in the value 1, hence the result 1000 + 1 = 1001 or 1 + 1000 = 1001, however, per the documentation, the behavior is undefined and should not be relied upon.

    If you've turned on E_NOTICE error reporting, a notice should also be produced, saying that object could not be converted to int.

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?