W3docs

How to fix 'Creating default object from empty value' warning in PHP?

This error typically occurs when a variable is accessed as an object, but it has not been initialized or set to an object.

This warning was introduced in PHP 7.2 and typically occurs when a variable is accessed as an object, but it has not been initialized or set to an object. To fix this, you can initialize the variable as an object before trying to access its properties or methods. For example, if you are trying to access a property called "name" on a variable called $obj, you can fix the error by initializing it first:

Example of initializing the variable before accessing a property in PHP

<?php

$obj = new stdClass();
$obj->name = "John";

echo $obj->name;

// Output:
// John

?>

Alternatively, you can use the null coalescing assignment operator (PHP 7.4+) for a more concise solution:

Example of using the null coalescing assignment operator in PHP

<?php

$obj ??= new stdClass();
$obj->name = "John";

echo $obj->name;

// Output:
// John

?>

You can also use the ternary operator to check if the variable is set before accessing it:

Example of using the ternary operator to check if the variable is set before accessing it in PHP

<?php

$obj = isset($obj) ? $obj : new stdClass();
$obj->name = "John";

echo $obj->name;

// Output:
// John

?>

It's also possible to use the isset() function to verify the variable exists:

Example of using the isset() function to check if the variable is set in PHP

<?php

if(isset($obj)){
    $obj->name = "John";
}else{
    $obj = new stdClass();
    $obj->name = "John";
}

echo $obj->name;

// Output:
// John

?>

Note: This warning strictly occurs when the variable itself is uninitialized or null. Accessing a non-existent property on an already initialized object will not trigger it. If you need to safely check for properties on an existing object, use property_exists():

Example of checking if a property exists on an initialized object in PHP

<?php

$obj = new stdClass();
if (property_exists($obj, 'name')) {
  echo $obj->name;
} else {
  echo 'not exists!';
}

?>

Make sure to check the context of your code and the variables you are using to identify the exact cause of the error and how to fix it.