Php warning create default object from empty ошибка

I see this error only after upgrading my PHP environment to PHP 5.4 and beyond. The error points to this line of code:

Error:

Creating default object from empty value

Code:

$res->success = false;

Do I first need to declare my $res object?

Michael Berkowski's user avatar

asked Jan 17, 2012 at 19:43

Paul's user avatar

3

Your new environment may have E_STRICT warnings enabled in error_reporting for PHP versions <= 5.3.x, or simply have error_reporting set to at least E_WARNING with PHP versions >= 5.4. That error is triggered when $res is NULL or not yet initialized:

$res = NULL;
$res->success = false; // Warning: Creating default object from empty value

PHP will report a different error message if $res is already initialized to some value but is not an object:

$res = 33;
$res->success = false; // Warning: Attempt to assign property of non-object

In order to comply with E_STRICT standards prior to PHP 5.4, or the normal E_WARNING error level in PHP >= 5.4, assuming you are trying to create a generic object and assign the property success, you need to declare $res as an object of stdClass in the global namespace:

$res = new stdClass();
$res->success = false;

answered Jan 17, 2012 at 19:45

Michael Berkowski's user avatar

Michael BerkowskiMichael Berkowski

267k46 gold badges442 silver badges389 bronze badges

15

This message has been E_STRICT for PHP <= 5.3. Since PHP 5.4, it was unluckilly changed to E_WARNING. Since E_WARNING messages are useful, you don’t want to disable them completely.

To get rid of this warning, you must use this code:

if (!isset($res)) 
    $res = new stdClass();

$res->success = false;

This is fully equivalent replacement. It assures exactly the same thing which PHP is silently doing — unfortunatelly with warning now — implicit object creation. You should always check if the object already exists, unless you are absolutely sure that it doesn’t. The code provided by Michael is no good in general, because in some contexts the object might sometimes be already defined at the same place in code, depending on circumstances.

answered Jan 8, 2014 at 20:10

Tomas's user avatar

TomasTomas

57.3k48 gold badges234 silver badges371 bronze badges

2

Simply,

    $res = (object)array("success"=>false); // $res->success = bool(false);

Or you could instantiate classes with:

    $res = (object)array(); // object(stdClass) -> recommended

    $res = (object)[];      // object(stdClass) -> works too

    $res = new stdClass(); // object(stdClass) -> old method

and fill values with:

    $res->success = !!0;     // bool(false)

    $res->success = false;   // bool(false)

    $res->success = (bool)0; // bool(false)

More infos:
https://www.php.net/manual/en/language.types.object.php#language.types.object.casting

answered Jan 17, 2016 at 18:25

pirs's user avatar

pirspirs

2,3702 gold badges17 silver badges25 bronze badges

4

If you put «@» character begin of the line then PHP doesn’t show any warning/notice for this line. For example:

$unknownVar[$someStringVariable]->totalcall = 10; // shows a warning message that contains: Creating default object from empty value

For preventing this warning for this line you must put «@» character begin of the line like this:

@$unknownVar[$someStringVariable]->totalcall += 10; // no problem. created a stdClass object that name is $unknownVar[$someStringVariable] and created a properti that name is totalcall, and it's default value is 0.
$unknownVar[$someStringVariable]->totalcall += 10; // you don't need to @ character anymore.
echo $unknownVar[$someStringVariable]->totalcall; // 20

I’m using this trick when developing. I don’t like disable all warning messages becouse if you don’t handle warnings correctly then they will become a big error in future.

answered Jul 4, 2017 at 12:59

kodmanyagha's user avatar

kodmanyaghakodmanyagha

93212 silver badges20 bronze badges

4

Try this if you have array and add objects to it.

$product_details = array();

foreach ($products_in_store as $key => $objects) {
  $product_details[$key] = new stdClass(); //the magic
  $product_details[$key]->product_id = $objects->id; 
   //see new object member created on the fly without warning.
}

This sends ARRAY of Objects for later use~!

answered Jun 12, 2015 at 9:00

Nickromancer's user avatar

NickromancerNickromancer

7,5418 gold badges58 silver badges76 bronze badges

1

answered Nov 30, 2020 at 13:46

bancer's user avatar

bancerbancer

7,4457 gold badges38 silver badges58 bronze badges

  1. First think you should create object
    $res = new stdClass();

  2. then assign object with key and value thay
    $res->success = false;

answered Apr 28, 2020 at 4:25

Sukron Ma'mun's user avatar

1

Try this:

ini_set('error_reporting', E_STRICT);

answered Sep 5, 2013 at 8:54

Irfan's user avatar

IrfanIrfan

4,81212 gold badges50 silver badges62 bronze badges

5

I had similar problem and this seem to solve the problem. You just need to initialize the $res object to a class . Suppose here the class name is test.

class test
{
   //You can keep the class empty or declare your success variable here
}
$res = new test();
$res->success = false;

answered Aug 6, 2018 at 8:06

Kevin Stephen Biswas's user avatar

Starting from PHP 7 you can use a null coalescing operator to create a object when the variable is null.

$res = $res ?? new stdClass();
$res->success = false;

Florian Rival's user avatar

answered Apr 12, 2022 at 13:30

Lost user's user avatar

A simple way to get this error is to type (a) below, meaning to type (b)

(a) $this->my->variable

(b) $this->my_variable

Trivial, but very easily overlooked and hard to spot if you are not looking for it.

mega6382's user avatar

mega6382

9,17117 gold badges47 silver badges69 bronze badges

answered Mar 15, 2016 at 9:01

Tannin's user avatar

1

You may need to check if variable declared and has correct type.

if (!isset($res) || !is_object($res)) {
    $res = new stdClass();
    // With php7 you also can create an object in several ways.
    // Object that implements some interface.
    $res = new class implements MyInterface {};
    // Object that extends some object.
    $res = new class extends MyClass {};
} 

$res->success = true;

See PHP anonymous classes.

answered Nov 15, 2017 at 20:08

Anton Pelykh's user avatar

Anton PelykhAnton Pelykh

2,2461 gold badge18 silver badges21 bronze badges

Try using:

$user = (object) null;

answered Nov 8, 2018 at 22:10

Fischer Tirado's user avatar

1

I had a similar problem while trying to add a variable to an object returned from an API. I was iterating through the data with a foreach loop.

foreach ( $results as $data ) {
    $data->direction = 0;
}

This threw the «Creating default object from empty value» Exception in Laravel.

I fixed it with a very small change.

foreach ( $results as &$data ) {
    $data->direction = 0;
}

By simply making $data a reference.

I hope that helps somebody a it was annoying the hell out of me!

answered Mar 14, 2019 at 4:56

Andy's user avatar

AndyAndy

3334 silver badges10 bronze badges

no you do not .. it will create it when you add the success value to the object.the default class is inherited if you do not specify one.

answered Jan 17, 2012 at 19:46

Silvertiger's user avatar

SilvertigerSilvertiger

1,6802 gold badges19 silver badges32 bronze badges

2

This problem is caused because your are assigning to an instance of object which is not initiated. For eg:

Your case:

$user->email = 'exy@gmail.com';

Solution:

$user = new User;
$user->email = 'exy@gmail.com';

answered Jun 8, 2014 at 4:46

Bastin Robin's user avatar

4

This is a warning which I faced in PHP 7, the easy fix to this is by initializing the variable before using it

$myObj=new stdClass();

Once you have intialized it then you can use it for objects

 $myObj->mesg ="Welcome back - ".$c_user;

answered Nov 4, 2019 at 14:52

Ayan Bhattacharjee's user avatar

I put the following at the top of the faulting PHP file and the error was no longer display:

error_reporting(E_ERROR | E_PARSE);

answered Feb 6, 2016 at 14:59

Doug's user avatar

DougDoug

5,09610 gold badges33 silver badges42 bronze badges

0

Unfortunately, if you get stuck in the error “Warning: creating default object from empty value” and don’t find out any method for this error. So, you don’t miss this blog. In today’s tutorial, we will give you simple ways to eliminate this problem. Now, let’s get started.

Warning: creating default object from empty value: What causes this error?

Usually, this error will come up, when you are trying to assign properties of an object without initializing an object.

In addition, this error will depend on the configuration in the PHP.ini file. Your new environment may have
E_STRICT
warning enabled in error reporting for PHP versions <=5.3.x or have
error_reporting
set to at least
E_WARNING
with PHP version >=5.4. This error is thrown once
$res
is
NULL
or not yet initialized.

$res = NULL;
$res->success = false; // Warning: Creating default object from empty value

So, what should you do to handle this problem? Below, we will provide you with 2 methods to help you easily get rid of this error.

How to resolve the error “Warning: creating default object from empty value”

Method 1:Create a
stdClass()
Object in PHP

This method allows you to declare a variable as an object of
stdClass()
in the global namespace, you can dynamically assign properties to the objects.

For example, if you generate a variable
$obj
and set it to
NULL
, then you set the
success
property to
false
with the
$obj
object. In this situation, the error will appear in the output section since
$obj
has not been initialized as an object.

Example code:

$obj = NULL;
$obj->success = true;

Then, the output:

Warning: Creating default object from empty value

So, to handle this error, you need to assign the
$obj
variable with the instance of
stdClass()
. Then, let’s set the
success
property to true with
$obj
.

Next, you need to use the
print_r()
function to print the
$obj
object. You can also utilize the
isset()
function to check if
$obj
has existed.

When you are done, you will see the information about
$obj
in the output section.

Example code:

$obj = new stdClass();
$obj->success =true;
print_r($obj);

Then, the output is:

stdClass Object ( [success] => 1 )

Method 2: Create Object from anonymous class in PHP

The second method helps you eliminate the error by creating an object from an anonymous class in PHP and assigning properties to it.

You are able to utilize the
new class
keyword to generate an anonymous class. Then, let’s set the value of the properties as in the generic class. Because the property will have a class, so you are able to access it with an object. As a result, the error will not appear.

For instance, if you generate an object
$obj
and assign an anonymous class by using the
new class
keyword to the object.

Then, you create a
public
property
$success
and set the value to
true
. And outside the class, you need to print the object with the
print_r()
function. This method will prevent your website from appearing the error by creating an object from an anonymous.

Example code:

$obj = new class {
public $success = true;
};
print_r($obj);

And the output is:

[email protected] Object ( [success] => 1 )

The bottom lines

Which method is valuable for your error? Let us know your experience and case by leaving a comment below. Moreover, if you are also dealing with any similar trouble, don’t hesitate to ask for our assistance. We will support you as soon as possible.

By the way, it is a great chance for you to drop by our free WordPress Themes to discover a bunch of eye-catching designs. Thank you for your reading!

  • Author
  • Recent Posts

Lt Digital Team (Content &Amp; Marketing)

Welcome to LT Digital Team, we’re small team with 5 digital content marketers. We make daily blogs for Joomla! and WordPress CMS, support customers and everyone who has issues with these CMSs and solve any issues with blog instruction posts, trusted by over 1.5 million readers worldwide.

Lt Digital Team (Content &Amp; Marketing)

Welcome to LT Digital Team, we’re small team with 5 digital content marketers. We make daily blogs for Joomla! and WordPress CMS, support customers and everyone who has issues with these CMSs and solve any issues with blog instruction posts, trusted by over 1.5 million readers worldwide.

Lt Digital Team (Content &Amp; Marketing)


Photo from Unsplash

The message PHP Warning: Creating default object from empty value appears when you assign property to an object without initializing the object first.

Here’s an example code that triggers the warning:

<?php
$user->name = "Jack";

In the code above, the $user object has never been initialized.

When assigning the name property to the $user object, the warning message gets shown:

Warning: Creating default object from empty value

To solve this warning, you need to initialize the $user object before assigning properties to it.

There are three ways you can initialize an object in PHP:

Let’s learn how to do all of them in this tutorial.

PHP initialize object with stdClass

The stdClass is a generic empty class provided by PHP that you can use for whatever purpose.

One way to initialize an object is to create a new instance of the stdClass() like this:

<?php
$user = new stdClass();
$user->name = "Jack";

After initializing the $user variable as an object instance, you can assign any property to that object without triggering the warning.

PHP initialize object by casting an array as an object

You can also cast an empty array as an object like this:

<?php
$user = (object)[];
$user->name = "Jack";

By casting an empty array as an object, you can assign properties to that object.

PHP initialize object by creating a new anonymous class instance

PHP also allows you to create a new anonymous class instance by using the new class keyword:

<?php
$user = new class {};
$user->name = "Jack";

The anonymous class instance will be an empty object, and you can assign properties to it.

Now you’ve learned how to solve the PHP Warning: Creating default object from empty value. Nice job! 👍

You logged in your WordPress to update and make a new post and ops what is this? An error message warning top of your dashboard and of course top of your website. This time it is like Warning! Creating default object from empty value in… 5 way to fix and hide this error.

WordPress 5.5.3 and below. This is the example error: Warning! Creating default object from empty value in /home/xxxxxx/public_html/xxxxx.com/wp-content/plugins/xxxx-addons/admin/ReduxCore/inc/class.redux_filesystem.php on line 29

As generally do, probably a plugin is causing this error, so lets find out which plugin is causing this error. You need to inactivate all your plugins one by one and then activate again all the plugins one by one to find out which one is the problematic one.

Okay let’s say you found out which plugin is it. If you think it is not a necessary plugin, until they fix the issue, you can inactivate that plugin and bam error is gone. So, you can keep continue to use, post and update your website.

But if the plugin is the major one, especially the one related to theme, you can’t just inactivate unless decide to use another theme, right? And your theme owner company is too busy to answer your questions about the fixing issue, host company is not helping either, and telling you that “go talk to your developer”. This may be one of those very frustrating issue.

Here you are a few easy fix to use on your WordPress to hide that error until someone really fix the plugin, you can use easily. Because this error is not causing any functional and working error, or making problem on your website, so just hiding the error message is enough for you for now.

How to Hide Error / Warning: Creating Default Object From Empty Value

1- On your .php folders find, wp-config.pgp (directly under your domain folder): Look at below code, this may not work with this error, but you can use to hide this for some other type of WordPress errors too.

define('WP_DEBUG', false);

2- Add below code to your .PHP file that sending the warning, just before the IF statement, somewhere beginning of the page and update the page.

error_reporting(E_Error);

3- This should stop the error too. Add it to your active themes functions.php (wp-content/themes/your theme/functions.php):

/* Stop errors if any /error_reporting(E_ERROR | E_PARSE);/ End stop Errors */

4- The following 2 lines should be added to to your .PHP file sending the warning just before the IF statement.

$query_context = new stdClass();
$query_context->context = array();

5- If other methods and codes didn’t work, then add those lines to your .PHP file sending the warning just before the IF statement.

/* suppress error with this */
ini_set('display_errors', 0);

$query_context = new stdClass();    
$query_context->context = array();

You can use Adobe DreamWeaver or any other type of program to edit and update your .php files or directly use your cPanel and edit in files section. So edit your file and update, and see if your error message is hide it and gone.

  1. Create a stdClass() Object in PHP
  2. Typecast Array Into Object in PHP
  3. Create Object From Anonymous Class in PHP

Create Default Object From Empty Value in PHP

We will introduce some methods for creating objects in PHP and solving the error creating default object from empty value.

Create a stdClass() Object in PHP

When we try to assign properties of an object without initializing an object, an error will be thrown. The error will say creating default object from empty value. The error also depends upon the configuration in the php.ini file. When the error is suppressed in the configuration, then such script will not throw the error. It is not better to change the configuration file to suppress the error to get rid of it. Instead, we can create a stdClass() object to get rid of the error. When we declare a variable as an object of the stdClass() in the global namespace, we can dynamically assign properties to the objects.

For example, create a variable $obj and set it to NULL. Then, set the success property to false with the $obj object. In this instance, an error will be thrown, as shown in the output section. It is because $obj has not been initialized as an object.

Example Code:

$obj = NULL;
$obj->success = true;

Output:

Warning: Creating default object from empty value

To eliminate the error, first, assign the $obj variable with the instance of stdClass(). Next, set the success property to true with the $obj. Then, print the $obj object using the print_r() function. It is even better to use the isset() function to check if $obj exists already. We can see the information about $obj in the output section. Thus, we can eliminate the error by creating an object of stdClass().

Example Code:

$obj = new stdClass();
$obj->success =true;
print_r($obj);

Output:

stdClass Object ( [success] => 1 ) 

Typecast Array Into Object in PHP

We can typecast an array to an object using the object keyword before the array. In this way, the object can be created. Then, we can assign the properties to the object. Since we already initialized the object, no error will be thrown while assigning properties of the object. This method also creates an object of the stdClass() class.

For example, create a variable $obj and assign it to the array() function. Then, write the object keyword in parenthesis before array(). The array has been converted into an object. Then, assign the true value to the success property with the $obj. Finally, print the object with the print_r() function. In this way, we can create an object typecasting an array and get rid of the error.

Example Code:

$obj = (object)array();
$obj->success =true;
print_r($obj);

Output:

stdClass Object ( [success] => 1 ) 

Create Object From Anonymous Class in PHP

We can create an object from an anonymous class in PHP and assign properties to it. We can use the new class keyword to create an anonymous class. We can set the value of the properties as in the generic class. Since the property will have a class, and we can access it with an object, no error will be thrown.

For example, create an object $obj assign an anonymous class using the new class keyword to the object. Then create a public property $success and set the value to true. Outside, the class, print the object with the print_r() function. In this way, we can create an object from an anonymous class in PHP and prevent the error.

Example Code:

$obj = new class {
 public $success = true;
};
print_r($obj);

Output:

class@anonymous Object ( [success] => 1 ) 

Понравилась статья? Поделить с друзьями:
  • Php out of memory ошибка
  • Php not found php server ошибка
  • Php mysql сообщения при ошибке
  • Photoshop не открывает pdf ошибка диска
  • Photoshop exe ошибка приложения 0xc0000142