Memory App
Php
 




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.

$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"
(1/3)

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
(2/3)

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.

// 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)
*/

Questions










Top Reference > Programming
0/0 (80)  
Save
4