Monday 2 February 2015

PHP Type Conversion & Casting

PHP Type Conversion & Casting

Numeric

$v = 1 + "3.5";                          # double(4.5)
$v = 2.3 + "some text";                  # double(2.3), String like "some text" is evaluated to 0
$v = 1 + "3 some text";                  # int(4)
$i = (int) 5/3;                          # $i = 1;

PHP Casting Function

Casting FunctionsComment
(int), (integer) 
(bool), (boolean) 
(float), (double), (real) 
(binary)cast to binary string
(object)cast to object
(unset)cast to NULL
 Float can be truncated to an integer using (int). If a function or operator is expecting an integer, the casting will be done automatically without (int).

Casting between PHP object and array

Convert a PHP Object to an array
class MyClass
{
    public $v1 = 'value';
}
$o = new MyClass;
$a = (array) $o;                      # Cast an object to an array
$a['v1'];                               # Access object instance variable $v1: 'value'
Convert an array to a PHP Object
$a = array('name' => 'value');
$o = (object) $a;                     # Cast an array to an ojbect
$o->name;                             # Access array element with key 'name': 'value'

PHP String Conversion

(string) converts other type to a string
$s = (string) FALSE;
$s = (string) "";
Conversion Rules
  • A TRUE value is converted to "1"
  • A FALSE value is converted to ""
  • Numeric value is converted to its corresponding number string
  • Array is convert to the string "Array"
  • Object is convert to the string "Object"

PHP Array Conversion

Cast to an array
$a = (array) "abc";
var_dump($a);          # array(1) { [0]=> string(3) "abc" }

Object

Convert to a PHP Object
$o = (object) 'hello';                   # Convert to object type
Convert from a PHP Object
echo $o->scalar;                         # 'hello'

0 comments:

Post a Comment