Categories
PHP

How to Fix WARNING: Creating default object from empty value

You may encounter this “warning” message when using PHP 5.4 or above

E_WARNING: Creating default object from empty value

Here is how to fix this 🙂

Sample code that generates error :

<?php
$a->b = 'something';
?>

How to fix :

<?php
if (is_null($a) || !is_object($a)) {
	$a = new stdClass();
}
$a->b = 'something';
?>

Sample code that generates error :

<?php
$a->b->c = 'something';
?>

How to fix :

<?php
if (is_null($a) || !is_object($a)) {
	$a = new stdClass();
}
if (is_null($a->b) || !is_object($a->b)) {
	$a->b = new stdClass();
}
$a->b->c = 'a';
?>

Leave a Reply

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