Question

Creating and Initializing Objects in PHP

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.

  • $res is the place where the folder should be stored.
  • success is a document inside that folder.
  • $res->success = false tries to put a document named success into 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.

Take Quiz

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:

  1. new stdClass() creates a new empty generic object.
  2. The assignment stores that object in $res.
  3. $res->success = false adds a success property to the object and gives it the Boolean value false.
  4. $res->statusCode = 400 adds 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, and statusCode.
  • 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);
Take Quiz

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 bool $success,
        public mixed $data = null,
        public ?string $error = null
    ) {
    }
}

function saveRecord(array $record): Result
{
    if (!isset($record['email'])) {
        return new Result(false, null, 'Email is required.');
    }

    return new Result(true, ['id' => 101]);
}

This pattern makes valid fields and their types explicit. It also uses an early return (a guard clause) to handle invalid input before continuing.

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 ->:

$res = [];
$res['success'] = false;

Using a variable before a function returns it

Broken:

function buildResponse(): void
{
    $res = new stdClass();
    $res->success = true;
}

$res->success = false;

The $res inside the function is local. Return it if code outside the function needs it:

function buildResponse(): stdClass
{
    $res = new stdClass();
    $res->success = true;
    return $res;
}

$res = buildResponse();
$res->success = false;

Comparisons

ChoiceCreate/access syntaxBest forNotes
stdClass object$res = new stdClass(); $res->success = false;Small, flexible objectsProperties can be added dynamically.
Associative array$res = []; $res['success'] = false;JSON-like and temporary dataUses [], not ->.
Custom class$res = new ApiResponse();Stable application modelsCan declare types, defaults, and methods.
null$res = null;Intentionally no valueIt is not an object and cannot safely hold properties.

A useful rule is: use an array for flexible key-value data, stdClass when an object shape is convenient but informal, and a custom class when the data has a defined meaning across your application.

Take Quiz

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 null or 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. $res->success accesses an object property. An array and an object are different PHP types.

Can I create properties dynamically on any PHP object?

Not always. stdClass is intended for flexible properties. In modern PHP, dynamically adding undeclared properties to many user-defined classes is discouraged or deprecated; declare the properties in the class instead.

Can I set an object property to false?

Yes. false is simply the property's value. The important requirement is that $res itself must be an object first.

Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more