Type casting = good coding practice?

Due to PHP's type juggling, it isn't usually necessary to make use of type casting.

I'm currently putting together a function which handles an integer, but makes use of several string functions along the way, which means the variable is constantly changing type, between an integer and a string.

Is it considered good coding practice to use type casting, to force PHP to maintain the intended variable type?


 $num = 21;
 $var = (int)str_pad($num,5,'0');

or perhaps even:

 $num = 21;
 $var = (int)str_pad((string)$num,5,'0');

Is this overkill? Is it sensible to use such coding practices in situations where it will make no difference to the execution of the code?
Who is Participating?

Type casting in most scripting languages, including php, happens automatically with primitive types like integers and strings, so the only time you should have to explicitly cast a variable is when the needed type is ambiguous. PHP in fact doesn't support defined types and in some cases will cast a variable even though you don't want it cast. This happens mostly with the "+" operator, although with all operators, functions and closures, PHP will automatically cast to an integer where one is required.

So for your code above:

$num = 21;
$var = str_pad($num,5,'0');
$big_num = $var + $var;
var_dump($big_num);// outputs 4200000

This is one of the reasons that PHP unlike some other languages provides an explicit string concatenatetor, the dot (.) operator, instead of just using the "+" operator. As long as you don't use the characters, "E","e","." inside of a string, PHP will always cast it to an interger where one is required.

So, yes, it is overkill. As to the practice of type casting in general, in object-oriented design, it has limited use other than in cases where there is ambiguity due to polymorphism.

In PHP you do not need to cast types at all... Only, if you need to calculate some decimals or you need to work with binary data (for example adding some information to binary type), then you can use the cast like this:
1. $i = (int)('123');
2. $i = int_val('123');

Try to use "..._val()" functions to cast the types.
Beverley PortlockCommented:
The only place you are in "danger" in PHP is when a value is zero. Sometimes this can mean FALSE or 0 or "" depending on where it is being used or inserted. I have seen

select * from table where val='$val'

evaluate to

select * from table where val=''

In such situations I tend to write

select * from table where val='".intval($val)."' so that I get

select * from table where val='0'
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.