PHP typecasting

后端 未结 6 1289
生来不讨喜
生来不讨喜 2020-12-05 06:46

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. <
6条回答
  •  鱼传尺愫
    2020-12-05 07:30

    It can depend on what types you're converting. PHP is already designed to convert types on-the-fly. It can convert the string '5' into the integer value 5 or float 5.0 if necessary. That's just PHP's natural type converting, but there are ways to force similar behaviours.

    In many cases intval() can actually be faster than (int) typecasting, especially in string-to-integer converting. But personally, as I also write C++, I use typecasting as it is more natural and neat to me. The results, however, vary slightly in different situations. I never thought of settype() to be promising, though.

提交回复
热议问题