PROGRAMMING

  minte9
learningjourney




S R Q

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    
Last update: 26 days ago