LateInit
LateInit is an interface. A class implements it to give a lateinit property its value the first time a program reads it.
The class writes one method, initProperty(string $name): void. A read of a lateinit property that has no value calls initProperty with the name of the property. The method sets the property, and then the read returns the new value. A later read does not call the method again.
If the property still has no value when initProperty returns, the read throws a LogicError. If the method throws an error, the next read calls it again.
Good to know: one call to initProperty may set several properties. A write that gives a property its first value inside initProperty does not run a set hook, PropertyGuard or PropertyObserver.
Examples
One load sets every property
<?nvs// Shows a user record that loads all its properties on the first read of any one// of them. `initProperty` runs once and sets three properties.
class User implements LateInit{ public lateinit string $name; public lateinit string $email; public lateinit int $logins;
public function initProperty(string $name): void { // A real program would read one row from a database here. echo 'loading the user, because ', $name, " was read\n"; $this->name = 'Ada'; $this->email = 'ada@example.com'; $this->logins = 3; }}
var $user = new User();
// The first read calls `initProperty`. The two reads after it call nothing.echo $user->email, "\n";echo $user->name, "\n";echo $user->logins, "\n";loading the user, because email was readada@example.comAda3