什么时候应该使用intval和什么时候int [复制]

时间:2022-09-10 22:58:23

This question already has an answer here:

这个问题在这里已有答案:

What is the better option:

什么是更好的选择:

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

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

Is there any difference between these two lines, and which should be used in which situation?

这两行之间有什么区别,应该在哪种情况下使用?

2 个解决方案

#1


20  

  1. intval is slower than casting to int (it's a function)
  2. intval比转换为int慢(它是一个函数)
  3. intval can accept a base if its first parameter is a string
  4. 如果第一个参数是字符串,则intval可以接受base

Since the second item is really obscure, objectively we should say that intval is simply "worse".

由于第二项非常模糊,客观上我们应该说intval只是“更糟糕”。

However, personally I like reading intval($var) better than (int)$var (the latter may also require wrapping in additional parens) and since if you are converting to int inside a loop you are definitely doing something wrong, I use intval.

但是,我个人喜欢读取intval($ var)比(int)$ var更好(后者也可能需要包装其他parens),因为如果你在循环中转换为int你肯定做错了,我使用intval 。

#2


5  

All behaviour explained here along with GOTCHAS...

所有行为都与GOTCHAS一起解释......

http://php.net/manual/en/function.intval.php

http://php.net/manual/en/function.intval.php

http://www.php.net/manual/en/language.types.type-juggling.php

http://www.php.net/manual/en/language.types.type-juggling.php

#1


20  

  1. intval is slower than casting to int (it's a function)
  2. intval比转换为int慢(它是一个函数)
  3. intval can accept a base if its first parameter is a string
  4. 如果第一个参数是字符串,则intval可以接受base

Since the second item is really obscure, objectively we should say that intval is simply "worse".

由于第二项非常模糊,客观上我们应该说intval只是“更糟糕”。

However, personally I like reading intval($var) better than (int)$var (the latter may also require wrapping in additional parens) and since if you are converting to int inside a loop you are definitely doing something wrong, I use intval.

但是,我个人喜欢读取intval($ var)比(int)$ var更好(后者也可能需要包装其他parens),因为如果你在循环中转换为int你肯定做错了,我使用intval 。

#2


5  

All behaviour explained here along with GOTCHAS...

所有行为都与GOTCHAS一起解释......

http://php.net/manual/en/function.intval.php

http://php.net/manual/en/function.intval.php

http://www.php.net/manual/en/language.types.type-juggling.php

http://www.php.net/manual/en/language.types.type-juggling.php