Php – the harm in ignoring “PHP Warning: Creating default object from empty value?”

PHP

It was recommended I ask this question here as it keeps getting downvoted on Stack overflow.

I am wondering What is the harm in ignoring PHP Warning: Creating default object from empty value?

I don't see any value in "fixing" it if the only thing I am doing is making this warning go away. Does PHP have intentions of making this warning into a fatal error in future versions?

Seems like it can create code bloat, especially in cases where you have dynamically created nested objects. This can be very painful to fix.

** I did search quite a bit to find an answer to this question in both google and stack overflow and feel like this is a good place to have this discussion even if the answers could just be an opinion. I would like to hear what others in the PHP community do to deal with this in their own code.

EXAMPLE

This will throw two of the aforementioned warnings

if(isset($foo) && isset($name)) {
    $bar->$name->schedule = $foo;
}

This will throw one warning

$bar = new stdClass();
if(isset($foo) && isset($name)) {
    $bar->$name->schedule = $foo;
}

This will throw no warnings

$bar = new stdClass();
if(isset($foo) && isset($name)) {
    $bar->$name = new stdClass();
    $bar->$name->schedule = $foo;
}

This is a basic example, but imagine if we had a huge array of dynamically generated $names that we had to wrap in a foreach loop and now we need to wrap our
$bar->$name = new stdClass(); in an if clause to ensure it does not already exist etc. The code starts to get unnecessarily bloated. So bloated I was already annoyed trying to write an example of what I meant. If left as the first one, things just nicely happen with just a few lines.

Best Answer

A warning is just that, a warning that a piece of code is potentially not what you intended.

I’m not familiar with this particular PHP warning and this is also not the place for discussion and opinion as you asked for, but sometimes it’s perfectly fine to ignore warnings. And other times not so much.

It’s up to the professional assessment of the programmer if a warning can or cannot be ignored in specific situations.

Some environments allow you to ignore certain warnings using configurations or tags or other techniques, which is sometimes useful to signal co-workers that a warning can be ignored for a valid reason.

The biggest problem with ignoring (not handling) warnings is that you become “immune” to warnings and you systematically ignore them. Once in a while you will miss an important one and cause a bug which could have been prevented early on in the development process.

So in general I prefer to either fix the warning, or use a technique to remove the warning if it’s invalid for the specific piece of code I’m working on.

Related Topic