【问题标题】:When should one use intval and when int [duplicate]什么时候应该使用 intval 什么时候使用 int [重复]
【发布时间】:2011-03-17 13:22:19
【问题描述】:

什么是更好的选择:

// Option 1:
$intValue = (int) $numericValue;

// Option 2:
$intValue = intval($numericValue);

这两行有什么区别,在什么情况下应该用哪一行?

【问题讨论】:

    标签: php


    【解决方案1】:
    1. intval 比转换为 int 慢(这是一个函数)
    2. intval 可以接受一个基数,如果它的第一个参数是一个字符串

    既然第二条实在是晦涩难懂,客观上我们应该说intval简直“更糟”了。

    但是,我个人更喜欢阅读 intval($var) 而不是 (int)$var(后者可能还需要用额外的括号括起来),因为如果你在循环中转换为 int 你肯定做错了什么,我使用intval.

    【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 2021-09-07
    • 2023-04-02
    • 2011-04-15
    • 2017-04-10
    • 2012-03-19
    • 2018-05-12
    • 2018-12-11
    相关资源
    最近更新 更多