We can change the type of variable with settype(). Then how is it different from casting?
The principle difference between settype() and a cast is the fact that casting produces a copy, leaving the original variable untouched.
In Casting:
$undecided = 3.14;
$holder = ( double ) $undecided;
print gettype( $holder ) ; // double
$holder = ( integer ) $undecided;
print gettype( $holder ); // integer
print ” — $holder<br />”; // 3
In settype():
$undecided = 3.14;
print gettype( $undecided ); // double
print ” — $undecided<br />”; // 3.14
settype( $undecided, int );
print gettype( $undecided ); // integer
print ” — $undecided<br />”; // 3
It is certainly not a procedure you will use often because PHP automatically casts for you when the context requires. However, an automatic cast is temporary, and you might want to make a variable persistently hold a particular data type.
Numbers typed in to an HTML form by a user are made available to your script as a string when entered in the text box. If you try to add two strings containing numbers, PHP helpfully converts the strings into numbers while the addition is taking place. So
“30cm” + “40cm”
produces the integer 70.
In casting the strings, PHP ignores the non-numeric characters. However, you might want to clean up your user input yourself. Imagine that a user has been asked to submit a number. We can simulate this by declaring a variable and assigning to it, like so:
$test = “30cm”;
As you can see, the user has mistakenly added units to the number. We can ensure that the user input is clean by casting it to an integer, as shown here:
$test = (integer)$test;
print “Your imaginary box has a width of $test centimeters”;
Leave a Reply
You must be logged in to post a comment.