How to Create an Object Without Class in PHP ?
In PHP, creating an object without a class refers to creating an instance of the stdClass, a built-in PHP class for creating generic objects. It allows developers to instantiate objects without explicitly defining a custom class, often used for dynamic data storage.
In this article, we will create an object without using a class in PHP.
Table of Content
Using new stdClass()
The new stdClass() approach in PHP allows you to create a generic object without defining a custom class. After creating an instance of stdClass, properties can be dynamically added, making it useful for temporary data storage or simple object structures.
Syntax:
// Creating an object
$object = new stdClass();
// Property added to the object
$object->property = 'Property_value';
Example : In this example we demonstrates the creation of an object using stdClass. It dynamically adds two properties, name and address, to the object, and then prints the object using print_r().
<?php
// Create an Object
$object = new stdClass();
// Added property to the object
$object->name = 'GeeksforGeeks';
$object->address = 'Noida';
// Print the object
print_r($object);
?>
Output
stdClass Object ( [name] => GeeksforGeeks [address] => Noida )
Converting an Array to an Object
The Converting an Array to an Object approach in PHP involves typecasting an associative array into an object. Each key in the array becomes a property of the object, allowing dynamic access to the values through object notation.
Syntax:
// Declare an array
$arr = array(
key1 => val1,
key2 => val2,
...
);
// Typecast to convert an array into object
$obj = (object) $arr;
Example : In this example we converts an associative array into an object using typecasting. Each array key becomes an object property. The print_r() function is used to display the resulting object with its properties.
<?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 )
Using json_decode with an Empty Object
The json_decode() function in PHP is used to decode a JSON string into a PHP object. By passing an empty JSON object ('{}'), you can create an object without a predefined class, and dynamically add properties as needed.
Example: In this example we use json_decode() to convert an empty JSON object into a PHP object. It dynamically adds properties property1 and property2, then displays the object using print_r().
<?php
$json = '{}'; // Empty JSON object
$obj = json_decode($json); // Convert JSON to PHP object
$obj->property1 = "value1"; // Dynamically add properties
$obj->property2 = "value2";
print_r($obj); // Print the object
?>
Output
stdClass Object ( [property1] => value1 [property2] => value2 )