Wednesday, September 3, 2025
HomeLanguagesHow to Create an Object Without Class in PHP ?

How to Create an Object Without Class in PHP ?

An object is an individual instance of the data structure defined by a class. We define a class once and then make many objects that belong to it. Objects are also known as instances. 

In this article, we will create an object without using a class in PHP.

Using new stdClass() to create an object without class: For creating an object without a class, we will use a new stdClass() operator and then add some properties to them.

Syntax:

// Creating an object
$object = new stdClass();

// Property added to the object
$object->property = 'Property_value';

Example1: The following code demonstrates the new stdClass() method.

PHP




<?php
  
    // Create an Object
    $object = new stdClass();
  
    // Added property to the object
    $object->name = 'neveropen';
    $object->address = 'Noida';
  
    // Print the object
    print_r($object);
  
?>


Output

stdClass Object
(
    [name] => neveropen
    [address] => Noida
)

Convert an array into an object without class: We will create an associative array with the list of keys and values, and after that, we use typecast to convert the array into an object. 

Syntax:

// Declare an array
$arr = array(
    key1 => val1,
    key2 => val2, 
    ...
);

// Typecast to convert an array into object
$obj = (object) $arr;

Example 2: The following code demonstrates the conversion of an array into an object without a class.

PHP




<?php
  
      // Create an associative array
      $studentMarks = array(
          "Biology"=>95, 
          "Physics"=>90,  
          "Chemistry"=>96, 
          "English"=>93,  
          "Computer"=>98
      );
  
      // Use typecast to convert
      // array into object
      $obj = (object) $studentMarks;
  
      // Print the object
      print_r($obj);
  
?>


Output

stdClass Object
(
    [Biology] => 95
    [Physics] => 90
    [Chemistry] => 96
    [English] => 93
    [Computer] => 98
)
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11854 POSTS0 COMMENTS
Shaida Kate Naidoo
6746 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS