Memory App

Building memory bonds
Php  >     ZCE 5.3  |  Patterns  |  Modern Php Php   >   Variables   >   Type casting


Type casting in PHP works much as it does in C. The name of the desired type is written in parentheses before the variable which is to be cast.

$arr1 = array(1, 2, 3);
$arr2 = (string) $arr1;

// array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }

// string(5) "Array"

Array to object

You can call an array item like object property if you type cast array to object.

$arr = array('senderId' => 10);

$obj = (object) $arr;

echo $obj->senderId; // Outputs: 10


stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces. When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

// create new object

$obj = (object) array(); // OR
$obj = new stdClass();
$obj->key1 = "value1";
$obj->key2 = "value2";


      public 'key1' => string 'value1' (length=6)
      public 'key2' => string 'value2' (length=6)