views:

36

answers:

2

I was reading some code that a consultant provided us. It's a bit convoluted, and at the end of a function, it reads:

return (int) 1;

Instead of:

return 1;

PHP has a lot of magic in it; is this as bone-headed as it looks, or is there a valid reason to cast an integer as an integer?

+5  A: 

No, it's the same. 1 is an integer literal.

See here these are all integer literals; casting to int has no effect:

$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)

If you did return "1"; that would be an entirely different matter. There are some differences in behaviour between "1" (string) and 1 (int), namely with bitwise operators.

Artefacto
+1  A: 

It's pretty bone headed. Integer literals are, well... integers.

1 === 1 however 1 !== '1'

also, when necessary, (as in this case it definitely isn't) I would suggest not typecasting with (int) use intval() instead.

jordanstephens
Why is that? ...
Inigoesdr
@Inigoesdr Why is what?
jordanstephens
Yeah, I wasn't clear: I would suggest not typecasting with (int) use intval() instead.
Inigoesdr
consider: `echo (int) 97.6 * 0.5; //prints 48.5` vs `echo intval(97.6 * 0.5); //prints 48`
jordanstephens