Sunday, June 30, 2013

Type Juggling and Type Casting



Type Juggling:
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

 
<?php
$foo = "0"; // $foo is string (ASCII 48)
$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
?>

Type Casting:
PHP is a loosely typed language and assigns types to variables depending what is assigned to it. Variables coming from get/post and cookies etc are generally cast as strings rather than other types and there are often other times when you need to specifically cast a type in PHP as e.g. an integer. This post looks at how to type cast in PHP and some of the results than can come about from type casting.


An example of this in action is as follows, where $foo starts off as a string value and is then cast into an integer:

$foo = '1';
echo gettype($foo); // outputs 'string'
settype($foo, 'integer');
echo gettype($foo); // outputs 'integer'

 

2 comments: