stdClass is a handy feature provided by PHP to create a regular class. It is a predefined 'empty' class used as a utility class to cast objects of other types. It has no parents, properties, or methods. It also does not support magic methods and does not implement any interfaces.

Creating stdClass Object

Example:

In the following example, stdClass is used instead of an array to store details:

<?php
$obj= new stdClass();
$obj->name= 'W3schools';
$obj->extension= 'In';
var_dump($object);
?>
Program Output:
object(stdClass)#1 (2) {
  ["name"]=>
  string(9) "W3schools"
  ["extension"]=>
  string(2) "In"
}

Whenever you need a generic object instance in your program, you can use stdClass because when you cast any other type to an object, you will get an instance of stdClass.

  • If an object is converted to an object using stdClass, it is not modified.
  • If the given value is NULL, the new instance will also be empty.
  • Arrays convert to an object with properties named by keys and associated values. It's like the alternative to associative arrays.
  • The member named scalar will contain the value for any other type of value.

Creating a stdClass Object by Type Casting

Example:

The following example shows that the value will be available in a member named Scalar when typecasting another type into an object:

<?php 
$obj= (object) 'W3schools';
var_dump($obj); // output in scalar
?>
Program Output:
object(stdClass)#1 (1) {
  ["scalar"]=>
  string(9) "W3schools"
}

Convert an Array into an Object

Example:

In the following example, an array is converted to an object by typecasting:

<?php 
$obj = array(
    'name'=>'W3schools',
    'Extension'=>'In',
);
$obj= (object) $obj;
var_dump($obj);
?>
Program Output:
object(stdClass)#1 (2) {
  ["name"]=>
  string(9) "W3schools"
  ["Extension"]=>
  string(2) "In"
}

Convert an Object into an Array

Example:

In the following example, an object is converted to an array by typecasting:

<?php
$obj= new stdClass();
$obj->name= 'W3schools';
$obj->extension= 'In';

$data = (array) $obj;
print_r($data);
?>
Program Output:
Array(
  [name] => W3schools
  [extension] => In
)

PHP differs from other object-oriented languages because classes in PHP do not automatically derive from any class. All PHP classes are standalone unless they are explicitly extended from another class. Here you can think of defining a class that expands stdClass, but it won't give you any benefit because stdClass does nothing.