How to use json_decode with an Empty Object In PHP
In PHP, the json_decode function transforms an empty JSON object into a PHP object. By assigning properties to this object dynamically, it serves as an ad hoc object instantiation method without the need for formal class definitions, facilitating flexible object creation.
Example
<?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 )
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';
Example 1: The following code demonstrates the new stdClass() method.
<?php
// Create an Object
$object = new stdClass();
// Added property to the object
$object->name = 'w3wiki';
$object->address = 'Noida';
// Print the object
print_r($object);
?>
Output
stdClass Object ( [name] => w3wiki [address] => Noida )