"Typed property must not be accessed before initialization" error when introducing properties type hints?

In PHP, the "Typed property must not be accessed before initialization" error is encountered when a property is defined with a type hint, but it is accessed before it has been explicitly assigned a value.

This error can be resolved by either providing a default value for the property or by initializing the property within the class constructor.

Watch a course Learn object oriented PHP

Here is an example of how to fix this error by providing a default value for the property:

<?php

// Define a new class called MyClass
class MyClass
{
  /**
   * @var int
   */
  // Define a private property called "myProperty" and initialize it to 0
  private int $myProperty = 0;

  // Define a public method called "getMyProperty" that returns the value of "myProperty"
  public function getMyProperty(): int
  {
    return $this->myProperty;
  }

  // Define a public method called "setMyProperty" that takes an integer value and sets "myProperty" to that value
  public function setMyProperty(int $value): void
  {
    $this->myProperty = $value;
  }
}

// Create a new instance of MyClass called "myObject"
$myObject = new MyClass();

// Call the "getMyProperty" method on "myObject" and store the result in a variable called "value"
$value = $myObject->getMyProperty();

// Output the value of "value"
echo "The initial value of myProperty is: " . $value . "\n";

// Call the "setMyProperty" method on "myObject" and set "myProperty" to 42
$myObject->setMyProperty(42);

// Call the "getMyProperty" method on "myObject" again and store the result in "value"
$value = $myObject->getMyProperty();

// Output the new value of "value"
echo "The new value of myProperty is: " . $value . "\n";

Alternatively, you can initialize it in the constructor

<?php

class MyClass
{
  /**
   * @var int
   */
  private int $myProperty;

  public function __construct()
  {
    $this->myProperty = 0;
  }

  public function getMyProperty(): int
  {
    return $this->myProperty;
  }

  public function setMyProperty(int $value): void
  {
    $this->myProperty = $value;
  }
}

// Example usage
$obj = new MyClass();
echo $obj->getMyProperty() . PHP_EOL; // Output: 0
$obj->setMyProperty(42);
echo $obj->getMyProperty(); // Output: 42

This way, when the class is instantiated, the interpreter can initialize the property with the default value or the one set in constructor and the error will be resolved.