What is PHP StdClass?

StdClass is a empty PHP class . You can set properties after creating a StdClass. You cannot add properties to already declared normal PHP class, but you can add properties with StdClass. Remember you cannot add method to StdClass.

StdClass is a empty PHP class used to add properties after initializing it. (Dynamic properties)

Sample StdClass

$user = new stdClass();
$user->name = "kinsly";
echo $user->name;

Initialize a stdClass and add dynamic properties is so simple as above example.

Casting with StdClass

Basically you can convert boolean, string, integer, array, associative array, JSON to stdClass. Below shows some of the usable casting types with stdClass.

Convert index Array to stdClass

$myArray = ['one','two', 'three', 'four', 'five'];
$myArrayObj = (object) $myArray;
echo $myArrayObj->{1};     //two

Convert Associative array to stdClass

$myArray = ['one'=>'Apple','two'=>"Banana", 'three'=>"Avacado", 'four' => "Pinapple", 'five' => "Guava"];
$myArrayObj = (object) $myArray;
echo $myArrayObj->one; //Apple

Convert JSON to stdClass

$json = '{"product": "Laptop", "price": 1200}'; 
$object = json_decode($json); 
echo $object->product; // Outputs: 1200