minte9
LearnRemember / 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.
 */

$A = array(1, 2, 3);
$B = (string) $A;

var_dump($A); // array(3) { ... }
var_dump($B); // string(5) "Array"

Object

You can call an array item like object property if you type cast array to object.
 
/**
 * Array to Object type casting
 */

$A = array('senderId' => 10);
$B = (object) $A;

echo $B->senderId; // 10

stdClass

In PHP the default object is of stdClass type.
 
/**
 * stdClass()
 * 
 * Is the default PHP object
 * Has no properties, methods or parent
 * 
 * When you cast an array as Object,
 * you get an instance of stdClass
 */

$A = (object) array(); // OR
$A = new stdClass();

$B = (object) [1, 2];
$B->x = "3";
$B->y = "4";

print_r($B); // stdClass Object( 0=>1, 1=>2, x=>3, y=>4)






Questions and answers




Which one is CORRECT?

  • a) $b = (int) $a;
  • b) $b = (int $a);

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

  • a) $obj = (object) $arr;
  • b) $obj = get_objects_var($arr);

How do you create new object?

  • a) $obj = (object) array();
  • b) $obj = new stdClass();
  • c) Using type casting or stdClass


References