Just for a moment, let me define type casting in case you weren’t “in the know”:
According to Wikipedia, “in computer science, type conversion or typecasting refers to changing an entity of one data type into another. “
So, in laymen terms, casting is an easy way to turn one type of data into another type. For example: converting a “string” variable filled with essentially text into an integer variable containing the same numbers but now representing a value. This makes it easy to do math with the value of what once was just a random string of characters.The following cast types are allow in PHP:
- String - (string)
- Boolean - (bool), (boolean)
- Integer - (int), (integer)
- Binary - (binary) [PHP 6]
- Floating Point - (float), (double), (real)
- Array - (array)
- Object - (object)
So, in the real world, when does casting actually come in handy?
Normally, PHP handles all this stuff automatically behind the scenes. But, as is normal, dealing with MySQL database interaction is something to always take seriously — and type casting can help you out!
So, your simplified (e.g. - don’t complain) database interaction code might look something like this:
$id = mysql_real_escape_string($_POST['input']);$SQL = 'SELECT * FROM table WHERE id = ' . $id;
Call me an overly nervous Ned, but I’d prefer to use the following code:$id = mysql_real_escape_string($_POST['input']);
$SQL = 'SELECT * FROM table WHERE id = ' . (int)$id;
Did you notice the subtle change? See the ‘int’ cast of the $id in the SQL statement?This should certainly help to ensure that I haven’t missed any security holes for this query. Some might say it’s overkill, but I just wanted a simple explanation for using casting, so get off your almighty soapbox already.
Anyways, as you can see, type casting in PHP has real-world uses. Delve into type casting a little more and you’ll find a huge number of cases where it can make your code that much more bullet-proof.So seriously, try out PHP Type Casting.
No comments:
Post a Comment