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.
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;
}
}
class Greet
{
public string $message = 'Welcome';
public function user(string $name): string
{
$greetings = sprintf('%s %s', $this->message, $name);
return $greetings;
}
}
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;
}
}