Open In App

How to Define an Empty Object in PHP ?

Last Updated : 05 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

An object is an instance of a class, and we can create objects using various approaches. Defining an empty object typically involves creating an instance without specifying a class definition explicitly. In this article, we will explore different approaches to defining an empty object in PHP, these are:

Approach 1: Using stdClass

The basic way to define an empty object in PHP is by using the stdClass class. This class is a built-in generic class that serves as a simple container for properties. It allows you to create objects on the fly without defining a specific class.

PHP




<?php
  
$emptyObject = new stdClass();
  
$emptyObject->propertyName = 'propertyValue';
  
echo $emptyObject->propertyName;
  
?>


Output

propertyValue

Approach 2: Using Casting to Object

Another approach is to use casting to convert an array or other data type into an object. This method is useful when you want to initialize an object with predefined properties.

PHP




<?php
  
$emptyObject = (object) [];
  
$emptyObject->propertyName = 'propertyValue';
  
echo $emptyObject->propertyName;
  
?>


Output

propertyValue

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads