Memory App
 



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

Parentheses

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;

var_dump($arr1);
// array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }

var_dump($arr2);
// string(5) "Array"
http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting

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
http://php.net/manual/en/language.types.object.php

stdClass

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";

var_dump($obj);

/*
object(stdClass)[1]
      public 'key1' => string 'value1' (length=6)
      public 'key2' => string 'value2' (length=6)
*/
https://stackoverflow.com/questions/1434368/how-to-define-an-empty-object-in-php