Why Typed Properties Break Doctrine Initialization Without Explicit Assignment
Introducing property type hints in PHP 8 is a powerful step toward catching null pointer exceptions early and enforcing stricter contracts on your data models. However, transitioning from loosely typed properties to strongly typed ones often triggers a specific runtime error when interacting with Doctrine ORM: Typed property must not be accessed before initialization. This error appears deceptively simple but points to a fundamental difference in how PHP handles uninitialized properties versus how Doctrine expects them to exist during the entity lifecycle.
The root cause lies in the order of operations between your constructor and Doctrine's hydration process. In standard PHP, when you declare private int $id; without a default value, that property is considered "uninitialized" until an assignment occurs. If you attempt to read or write to it before initialization, PHP throws a fatal error. This behavior is intentional to prevent silent bugs where properties hold garbage values or throw unexpected exceptions later in the execution flow.
Your provided example illustrates a common pattern:
class Foo {
private int $id;
private ?string $val;
private DateTimeInterface $createdAt;
private ?DateTimeInterface $updatedAt;
public function __construct(int $id) {
$this->id = $id;
}
// ... getters and setters ...
}
In this implementation, $id is guaranteed to be initialized immediately upon object creation because the constructor accepts it as a required argument. However, properties like $val, $createdAt, and $updatedAt are not assigned in the constructor. While your getters return these values with nullable type hints (?string, ?DateTimeInterface) or handle them gracefully, the underlying storage remains uninitialized until a setter is called.
The conflict arises because Doctrine does not always follow the standard PHP object lifecycle strictly when hydrating entities from the database. When Doctrine reconstructs an entity from a row in the database table, it often accesses properties to populate their values before the application's __construct method has been executedâor at least before your specific setters have run.
Specifically, if you access $this->val inside a getter during the hydration phase, or if Doctrine attempts to serialize/deserialize the object (e.g., in logging or cache storage), PHP checks if the property has been initialized. If the property was declared without a default value and hasn't been assigned yet, PHP throws the TypedPropertyError. This happens regardless of whether the property is nullable or not. The error message does not lie: the typed property literally has not been accessed for initialization purposes yet.
Solutions for Doctrine Compatibility
To resolve this without sacrificing the benefits of strict typing, you have two primary architectural options.
Option 1: Assign Default Values in Declaration
The most straightforward fix is to assign a default value to every property that might be accessed before initialization. For nullable properties, null is an appropriate default. For non-nullable types like int, you must use a sentinel value that makes semantic sense, or accept that the constructor must always run first.
class Foo {
private int $id = 0; // Default to 0 or handle as uninitialized flag
private ?string $val = null;
private DateTimeInterface $createdAt = new \DateTimeImmutable(); // Requires careful consideration
private ?DateTimeInterface $updatedAt = null;
public function __construct(int $id) {
$this->id = $id;
}
}
However, using new DateTimeImmutable() as a default can be problematic if Doctrine expects the column to be NULL in the database. It forces the database schema and your application logic to align on whether "no date" means null or a specific timestamp.
Option 2: Initialize Properties in the Constructor
A cleaner approach that preserves the meaning of uninitialized states is to ensure all properties are assigned inside the constructor. This works well if Doctrine guarantees the constructor runs before accessing these properties, which is often true for standard entity loading but not always during serialization or error handling.
class Foo {
private int $id;
private ?string $val = null; // Nullable properties can safely default to null
private DateTimeInterface $createdAt;
private ?DateTimeInterface $updatedAt = null;
public function __construct(int $id, ?DateTimeInterface $createdAt = null) {
$this->id = $id;
$this->createdAt = $createdAt ?? new \DateTimeImmutable('now');
}
}
Why This Matters for ORM Patterns
Understanding this limitation prevents a common pitfall: assuming that type hints alone are sufficient for safety. Type hints define the contract, but they do not guarantee initialization state. When using an ORM like Doctrine, you must account for the fact that the framework may inspect your object internals before your application logic has had a chance to set them.
If you encounter this error, check where the property is being read. Is it inside a getter called during hydration? Is it being serialized by var_export or serialize()? In these cases, ensuring the property holds a valid value (even null) at all times is mandatory.
For projects using modern tooling, you might also consider using #[Override] attributes or specific Doctrine annotations to hint that a property is managed by the ORM and should not be accessed directly in user code until initialization is complete. However, the safest path remains assigning default values that match your database schema's expectations for NULL vs. non-NULL columns.
