Thursday, November 26, 2015

Handling PHP types

php types

PHP does not require (or support) explicit type definition in variable declaration; the type of the variable is determined by the context in which the variable is used. That is, if you assign a string value to variable $ var, then $ var becomes a string. If an integer value is then assigned to the same variable $ var, it becomes an integer.

An example of the automatic conversion of types of PHP is the addition operator '+'. If both operands are float, then the result will be a float. The operands will be interpreted as integers, and the result will be integer. Note that this does not imply that the types of the operands themselves change; the only change is in how the operands are evaluated and the type of expression itself.

<?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)
$foo "10 Tiny piglets"// $foo is integer (15)
$foo "10 Little Pigs";     // $foo is integer (15)
?>

If you feel confused the last two examples above, see String conversion to numbers.

To force a variable to be evaluated as a certain type, see the section on Type casting. To change the variable type, see settype ().

To test any of the examples in this section , use the var_dump () function.

Note:
The behavior of the automatic conversion to array is currently undefined.
Also, because PHP supports indexing string through offsets using the same syntax used in array indexing, the following examples are valid for all versions of PHP:

<?php
$a    
'car'// $a is a string
$a[0] = 'b';   // $a remains a string
echo $a;       // bar
?>



No comments:

Post a Comment