Question
After upgrading to PHP 5.4 or later, PHP reports the following error on this line:
$res->success = false;
Creating default object from empty value
Do I need to declare or initialize the $res object before assigning its success property?
Short Answer
You will learn why assigning a property requires an object, how PHP may try to create a default object from an empty value, and how to initialize $res explicitly with stdClass or a purpose-built class.
Concept
In PHP, the -> operator accesses a property or method on an object. Therefore, the variable on its left must already contain an object.
$res->success = false;
This code means: “Find the object stored in $res and set its success property to false.” If $res is undefined, null, false, or another non-object value, PHP cannot reliably perform that object-property assignment.
Older PHP versions sometimes implicitly converted an empty value into a generic object. PHP 5.4 made this situation more visible by reporting Creating default object from empty value. Rather than depending on implicit conversion, create the object deliberately.
For a small, flexible data container, use PHP's built-in stdClass:
$res = new stdClass();
$res->success = false;
For application data with known fields and behavior, define your own class instead. Explicit initialization makes the code clearer, avoids version-dependent warnings, and documents what $res is meant to contain.
Mental Model
Think of an object as a labeled folder that can hold named documents.
$resis the place where the folder should be stored.successis a document inside that folder.$res->success = falsetries to put a document namedsuccessinto the folder.
If no folder exists yet, PHP has nothing to put the document into. Creating the folder first with new stdClass() makes the operation explicit.
Syntax and Examples
Use new to create an object before setting properties.
$res = new stdClass();
$res->success = false;
$res->message = 'The request was processed.';
var_dump($res);
Output conceptually:
object(stdClass)#1 (2) {
["success"]=>
bool(false)
["message"]=>
string(26) "The request was processed."
}
stdClass is PHP's generic, empty object class. You can add properties to it dynamically.
For data with a known structure, a custom class is usually clearer:
class ApiResponse
{
public bool $success;
public string $message;
}
$res = new ApiResponse();
$res->success = false;
$res->message = 'Invalid request.';
In modern PHP, declaring properties makes the expected shape of the object visible and helps tools detect mistakes.
Step by Step Execution
Consider this code:
$res = new stdClass();
$res->success = false;
$res->statusCode = 400;
Execution proceeds as follows:
new stdClass()creates a new empty generic object.- The assignment stores that object in
$res. $res->success = falseadds asuccessproperty to the object and gives it the Boolean valuefalse.$res->statusCode = 400adds another property to the same object.
Afterwards, $res represents data similar to:
object(stdClass) {
success: false,
statusCode: 400
}
Without the first line, $res has no initialized object for ->success to target.
Real World Use Cases
Object initialization appears frequently in PHP applications:
- API responses: Store fields such as
success,data,error, andstatusCode. - Database records: Represent a row returned from a query as an object.
- Configuration data: Group related settings under named properties.
- Service results: Return both a result value and information about failures.
- Template/view data: Pass a structured object containing values a page needs to render.
For example, a small API response object can be built explicitly:
$response = new stdClass();
$response->success = true;
$response->data = ['id' => 42, 'name' => 'Ada'];
header('Content-Type: application/json');
echo json_encode($response);
Real Codebase Usage
In production code, developers typically avoid creating loosely shaped objects throughout the application. They initialize values explicitly and choose an appropriate data structure.
Return a structured result
function findUser(int $id): array
{
if ($id <= 0) {
return [
'success' => false,
'error' => 'An ID must be positive.',
];
}
return [
'success' => true,
'data' => ['id' => $id, 'name' => 'Ada'],
];
}
Arrays are often convenient for JSON-like payloads because they work naturally with json_encode().
Use a dedicated class for a stable contract
class Result
{
public function __construct(
public ,
= ,
? =
) {
}
}
{
(!([])) {
(, , );
}
(, [ => ]);
}
Common Mistakes
Assigning a property before creating the object
Broken:
$res->success = false;
If $res has not been initialized as an object, PHP can emit a notice or warning such as Creating default object from empty value.
Fix:
$res = new stdClass();
$res->success = false;
Overwriting the object with a non-object value
Broken:
$res = new stdClass();
$res = false;
$res->success = false;
The second line replaces the object with a Boolean. Keep the object intact, or create a new object before accessing properties.
Using -> with an array
Broken:
$res = [];
$res->success = false;
Arrays use square-bracket syntax, not :
Comparisons
| Choice | Create/access syntax | Best for | Notes |
|---|---|---|---|
stdClass object | $res = new stdClass(); $res->success = false; | Small, flexible objects | Properties can be added dynamically. |
| Associative array | $res = []; $res['success'] = false; | JSON-like and temporary data | Uses [], not ->. |
| Custom class | $res = new ApiResponse(); | Stable application models | Can declare types, defaults, and methods. |
null | $res = null; |
Cheat Sheet
// Generic object: initialize first
$res = new stdClass();
$res->success = false;
// Read a property
if ($res->success === false) {
echo 'Failed';
}
// Array alternative
$res = [];
$res['success'] = false;
// Custom class alternative
class Response
{
public bool $success = false;
}
$res = new Response();
- Use
->for object properties and methods. - Use
['key']for array elements. - Initialize an object before assigning properties.
new stdClass()creates a generic empty object.- Do not rely on PHP implicitly converting
nullor another empty value into an object. - Use a custom class when a response has a known, reusable structure.
FAQ
What does “Creating default object from empty value” mean in PHP?
It means PHP encountered a property assignment such as $res->success = false when $res did not contain an initialized object. Older behavior could create a generic object implicitly, but code should initialize it explicitly.
How do I fix $res->success = false?
Create the object first:
$res = new stdClass();
$res->success = false;
Do I have to declare an object variable in PHP?
PHP does not require a separate declaration, but you must assign an object to the variable before accessing object properties. new stdClass() or new YourClass() does that.
Should I use stdClass or an array?
Use stdClass if object-property syntax is useful. Use an associative array for flexible key-value data. For important, repeatable application data, prefer a dedicated class.
Why does $res['success'] work differently from $res->success?
$res['success'] accesses an array element. accesses an object property. An array and an object are different PHP types.
Mini Project
Description
Build a small response factory for a command-line script. It creates explicit response objects for successful and failed operations, demonstrating that properties are only assigned after an object exists.
Goal
Create and print success and error response objects without relying on PHP's implicit object creation.
Requirements
Initialize every response as an object before assigning properties. Create one successful response containing data. Create one failed response containing an error message. Encode both responses as JSON for output.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.