Go Back   CP Web Hosting - reseller hosting > Server Scripting > PHP
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 06-21-2007, 12:40 PM
Junior Member
 
Join Date: May 2007
Posts: 19
Default settype() different from casting

We can change the type of variable with settype(). Then how is it different from casting?
Reply With Quote
  #2 (permalink)  
Old 06-21-2007, 12:46 PM
Junior Member
 
Join Date: Apr 2007
Posts: 5
Default

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";
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT. The time now is 02:15 PM.


Powered by vBulletin® Version 3.6.5
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO 3.1.0