PHP 类型转换

2021-12-25 00:00:00 types casting php

我想知道将值从一种类型转换为另一种类型的最佳方法是什么.

I was wondering what is the best way to typecast a value from one type to another.

我们应该使用哪种变体:

Which variant should we use:

  1. intval($value);
  2. settype($value, 'int')
  3. (int)$value

所有这些都产生相同的结果.

All of them produce same result.

推荐答案

(int)$value

intval($value)settype($value, 'int') 相比,节省了一个函数调用.

saves one function call compares to intval($value) and settype($value, 'int').

而且 (int)$value 已经足够干净了,所以我更喜欢这种方式.

And (int)$value is clean enough, so I prefer this way.

When you need to use intval($value) 是当你需要使用指定的基数进行转换时(默认为基数 10).intval 接受第二个参数作为转换的基础.

When you need to use intval($value) is that when you need to use the specified base for the conversion (the default is base 10). intval accepts a second parameter for the base for the conversion.

相关文章