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条)

报告相同问题?

悬赏问题

  • ¥200 关于#c++#的问题,请各位专家解答!
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀