Changing Type by CASTING a Variable

Chapter 5 #95 - Martha's CIS 52

ASSIGNMENT/EXPLANATION

CASTING changes the type of a variable by producing a copy of it, and leaving the original variable untouched.
gettype() is used to produce the original variable; however, it will likely be deprecated, and programmers should use the is_* family instead.
An answer of "1" means it's true (it is a variable of that type); no answer means it is false (it is not a variable of that type).

NOTICE: When casting a string into an integer or a float, PHP ignores any nonnumeric characters, and any characters from the first nonmeric character on will be ignored.

REMEMBER: PHP automatically casts variables when the ontext of the script requires a change. BUT, this is only temporary. Casting allows you to maintain the type of variables you want changed.

Exercise

Is 3.14 a double? 1
Is 3.14 a string? 1
Is 3 a integer? 1
Is 3.14 a double? 1
Is 1 a boolean? 1

The original variable type of 3.14: double

CODE

$undecided = 3.14;
$holder = (double) $undecided;
echo "Is ".$holder." a double? ".is_double($holder)."<br />"; // double
$holder = (string) $undecided;
echo "Is ".$holder." a string? ".is_string($holder)."<br />"; // string
$holder = (integer) $undecided;
echo "Is ".$holder." a integer? ".is_integer($holder)."<br />"; // integer
$holder = (double) $undecided;
echo "Is ".$holder." a double? ".is_double($holder)."<br />"; // double
$holder = (boolean) $undecided;
echo "Is ".$holder." a boolean? ".is_bool($holder)."<br />"; // boolean
echo "<hr />";
echo "The original variable type of $undecided: ";
echo gettype($undecided); // double