Avatar ·

Error "Creating default object from empty value" in PHP: causes and fix

Hello everyone! I just started learning PHP and encountered a strange error that I can't understand.

\n\n

I have a simple code where I'm trying to create an object and immediately assign a property to it:

\n\n
<?php\n$user = new stdClass();\n$user->name = 'John';\n$user->age = 25;\n\n// Then I decided to simplify and wrote this:\n$user2->name = 'Jane'; // This is where the error occurs!\n?>
\n\n

I get a warning: "Creating default object from empty value". Earlier in tutorial examples, I saw that you could write $obj->property = value without declaring $obj = new stdClass(), and it worked. But now PHP complains. Why is this happening?

\n\n

I understand that $user2 is not defined, but shouldn't PHP create it automatically?