PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I'm very used to C++ and am still getting used to the differences in PHP. One that concerned me was typecasting. I have discovered that PHP can type cast similarly to C++, but also have functions to do these for me. I was wondering if I should break my habit of C-style typecasting, or if it's acceptable. For example:
intval() does not change the type of the var, it returns the integer value of the var. You can still use the type casting syntax you posted to type cast in PHP.
I sometimes typecast rather than validate. It's me being lazy but it's prefectly acceptable IMHO. I only do that in places where the result of say, a string "x" being cast as int would produce result which didn't break anything.
I often cast (array) where the parameter can optionally be a single value, or a collection of values, so that it's always a collection when I work with it.
2. I find intval() to be the more readable variant of the two, but IIRC someone here said that internally casting and calling the function do the same. Moreover (esp. if you find loose typing confusing) you may try some form of Hungarian notation (I use $nNumber, $sString, $aArray, $pObject, $bBoolean, $fFloat) to keep track of the variables.
Mordred wrote:you may try some form of Hungarian notation (I use $nNumber, $sString, $aArray, $pObject, $bBoolean, $fFloat) to keep track of the variables.
Mordred wrote:you may try some form of Hungarian notation (I use $nNumber, $sString, $aArray, $pObject, $bBoolean, $fFloat) to keep track of the variables.
Mordred wrote:
2. I find intval() to be the more readable variant of the two, but IIRC someone here said that internally casting and calling the function do the same.
Through testing I found the intval to be about 10 times slower compared to (int). Maybe it is because intval understands hexadecimal strings.
I had never heard of it before coming here for help. When I first saw code that did that I thought to myself 'What the bloody hell is all this $iInt, $strString crap?!?!?!'
Well it was something that I kept in C++ and have stayed true to. Especially since PHP has the ability to suddenly change types... It helps me notice an accidental change.
And just my two cents... Java Runtime... I feel so helpless programming in Java. JavaScript is nothing, but Java feels like C++... until you try to do anything. :-p