PHP

PHP

Made by DeepSource

Typed property accessed before initialization PHP-E1008

Bug risk
Major

The typed properties must not be accessed before initialization. That means the property is in Uninitialized state, so reading from the property will result in a fatal runtime error.

To avoid this problem it is recommended to give it a default value or assign it to the constructor.

Bad practice

class Greet
{
    public string $message;

    public function user(string $name): string
    {
        // invalid: $message property is uninitialized
        $greetings = sprintf('%s %s', $this->message, $name);

        return $greetings;
    }
}

Recommended

Consider giving it a default value:

class Greet
{
    public string $message = 'Welcome';

    public function user(string $name): string
    {
        $greetings = sprintf('%s %s', $this->message, $name);

        return $greetings;
    }
}

Initialize the property in constructor:

class Greet
{
    public string $message;

    public function __construct(string $message)
    {
        $this->message = $message;
    }

    public function user(string $name): string
    {
        $greetings = sprintf('%s %s', $this->message, $name);

        return $greetings;
    }
}

References