Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Typed property must not be accessed before initialization in PHP

ErrorFatal error: Uncaught Error: Typed property App\User::$name must not be accessed before initialization

Short answer

A typed property with no default has no value at all until you assign one, and reading it throws an Error. Assign it in the constructor or before the first read, or give it a constant default. A nullable type does not set null by itself: add = null explicitly.

  • Applies to PHP 8.3, PHP 8.4
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Find the property named in the message and look for every place it is assigned. The error means the read ran before any assignment.

    grep -rn "numberOfSides" src/
  2. 2Match what you see, then jump to its fix

    1. 1The error names a property and the stack trace points to a getter.The property is only set by a setter or a later methodFix
    2. 2The property is declared as ?string or ?int and you expected null.A nullable type was declared but no default null was writtenFix
    3. 3The error happens only for objects loaded with PDO::FETCH_CLASS, inside the constructor.The constructor reads columns that PDO fills in later (FETCH_PROPS_LATE)Fix
    4. 4The property is declared readonly and has no default.A readonly property is read before its first (and only) writeFix

What does the error look like?

  • Fatal error: Uncaught Error: Typed property App\User::$name must not be accessed before initialization
  • Typed property Shape::$numberOfSides must not be accessed before initialization

Cause 1 of 4

The property is only set by a setter or a later method

1Check

Typed properties do not start as null. They stay uninitialized until something assigns them, and reading them first throws an Error.

grep -n "function __construct" src/Shape.php
grep -n "this->numberOfSides =" src/Shape.php

2Fix

Assign the property in the constructor so every object is valid from the start. If a sensible starting value exists, put it in the declaration (it must be a constant expression).

class Shape
{
    public function __construct(
        private int $numberOfSides,
        private string $name = 'unnamed',
    ) {}
}

3Verify

Create the object and call the getter straight away.

php -r 'require "src/Shape.php"; echo (new Shape(3))->getNumberOfSides();'

Confirmed by php.net

Did this fix it?

Cause 2 of 4

A nullable type was declared but no default null was written

1Check

The manual's nullable example assigns the value in the constructor. The type only allows null; the declaration does not initialize it, so an unassigned ?string property is still uninitialized.

grep -rn "public ?\|private ?\|protected ?" src/

2Fix

Write the default in the declaration.

class User
{
    public ?string $name = null;
    public int $id;
}

3Verify

Read the nullable property on a fresh object; it now returns null.

php -r 'class U { public ?string $n = null; } var_dump((new U)->n);'

Confirmed by php.net

Did this fix it?

Cause 3 of 4

The constructor reads columns that PDO fills in later (FETCH_PROPS_LATE)

1Check

By default PDO::FETCH_CLASS maps columns to properties before the constructor runs. With PDO::FETCH_PROPS_LATE the order reverses: the constructor runs first, then the properties are assigned. A constructor that reads a typed property in that mode sees it uninitialized.

grep -rn "FETCH_PROPS_LATE" src/

2Fix

Move the logic that needs those values out of the constructor into a method called after the fetch, or drop FETCH_PROPS_LATE if the constructor does not need to run first. Also note that column values are not passed to the constructor.

$stmt->setFetchMode(PDO::FETCH_CLASS, User::class);
$user = $stmt->fetch();
$user->init();   // your method that uses the loaded values

3Verify

Fetch one row and read the property.

var_dump($user->name);

Confirmed by php.net

Did this fix it?

Cause 4 of 4

A readonly property is read before its first (and only) write

1Check

A readonly property cannot have a default value, and it can only be initialized once, from inside the class. Until that happens it is uninitialized.

grep -rn "readonly" src/

2Fix

Initialize it in the constructor. Do not try to give it a default.

class Test
{
    public readonly string $prop;
    public function __construct(string $prop)
    {
        $this->prop = $prop;
    }
}

3Verify

Construct the object and read the property.

php -r 'class T { public function __construct(public readonly string $p) {} } echo (new T("ok"))->p;'

Confirmed by php.net

Did this fix it?

How do I stop it coming back?

  • Initialize every typed property in the constructor, or give it a constant default in the declaration.
  • Use constructor property promotion so declaration and assignment are one line.
  • Write ?type = null whenever null is the intended starting value.
  • Avoid reading properties inside a constructor of objects that PDO fills after construction.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

Apache returns 403 when a URL contains %3F

a request like /page%3Fname=test is refused while /page?name=test works

Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.

2 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.