What is stdClass in PHP?

Overview

The stdClass is a generic empty class used to cast the other type values to the object. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. The stdClass is not the base class for objects in PHP.

Example

<?php
// when we typecast one type to object we will get stdClass
$obj = (object) 'Educative';
var_dump($obj);
// The value of the object is present in scalar property
echo $obj->scalar;
?>

We type-cast the string 'Educative' to an object in the code above. As a result of this, we get an stdClass object. The string value will be present in the scalar property of the stdClass object.

How to convert an array to an object

<?php
$user = array(
'name'=>'Raju',
'address'=>'Hosur',
);
$userObj = (object) $user;
var_dump($userObj);
?>

We create an array with the name user. Then we type-cast the array to an object. As a result of this, we get an stdClass object.

Free Resources