PHP: Create empty object – new stdClass,var_dump

Generating Random String Using PHP

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

Standard way to create an “empty” object is:

<?php 

$input_object = new stdClass();
var_dump($input_object);

?>

Result for new stdClass():

object(stdClass)#1 (0) {
}

But, with PHP Version >= 5.4, I recommend to use:

<?php 

$input_object = (object)[];
var_dump($input_object);

?>

Result for (object)[]:

object(stdClass)#1 (0) {
}

In PHP, it is also possible to use type casting to convert a simple empty array into a stdClass object.

Note the typecasting with (object) just before the array will does the work of converting the simple array into a stdClass object.

<?php 

$input_object = (object)array();
var_dump($input_object);

?>

Result for (object)array():

object(stdClass)#2 (0) {
}

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *