Wednesday, September 29, 2010

Changing Data Type Type by Casting in Php

By placing the name of a data type in brackets in front of a variable, you create a
copy of that variable's value converted to the data type specified. The principal
difference between settype() and a cast is the fact that casting produces a copy,
leaving the original variable untouched. Listing 4.6 illustrates this.

1: <html>
2: <head>
3: <title>Listing 4.6 Casting a variable</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: $holder = ( double ) $undecided;
9: print gettype( $holder ) ; // double
10: print " -- $holder<br>"; // 3.14
11: $holder = ( string ) $undecided;
12: print gettype( $holder ); // string
13: print " -- $holder<br>"; // 3.14
14: $holder = ( integer ) $undecided;
15: print gettype( $holder ); // integer
16: print " -- $holder<br>"; // 3
17: $holder = ( double ) $undecided;
18: print gettype( $holder ); // double
19: print " -- $holder<br>"; // 3.14
20: $holder = ( boolean ) $undecided;
21: print gettype( $holder ); // boolean
22: print " -- $holder<br>"; // 1
23: ?>
24: </body>
25: </html>
We never actually change the type of $undecided, which remains a double
throughout. In fact, by casting $undecided, we create a copy that is then converted
to the type we specify. This new value is then stored in the variable $holder.
Because we are working with a copy of $undecided, we never discard any
information from it as we did in Listing 4.5.

No comments:

Post a Comment