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?
asked Jan 17, 2012 at 19:43
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 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
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
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
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
NickromancerNickromancer
7,5418 gold badges58 silver badges76 bronze badges
1
answered Nov 30, 2020 at 13:46
bancerbancer
7,4457 gold badges38 silver badges58 bronze badges
-
First think you should create object
$res = new stdClass(); -
then assign object with key and value thay
$res->success = false;
answered Apr 28, 2020 at 4:25
1
Try this:
ini_set('error_reporting', E_STRICT);
answered Sep 5, 2013 at 8:54
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
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;
answered Apr 12, 2022 at 13:30
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
9,17117 gold badges47 silver badges69 bronze badges
answered Mar 15, 2016 at 9:01
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 PelykhAnton Pelykh
2,2461 gold badge18 silver badges21 bronze badges
Try using:
$user = (object) null;
answered Nov 8, 2018 at 22:10
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
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
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
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
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
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
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.
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.