Properties and constants
A property is written as visibility type $name, with an optional default:
public int $size = 8;. A class constant is written as visibility const type NAME = value;.
Inside the class you read it as self::NAME, and outside it as Config::NAME.
Properties and constants
A property is a variable that belongs to an object. A class constant is a value that belongs to the class and never changes.
You write a property as visibility [static] type $name, with an optional default value: public int $size = 8;. Each object has its own copy of every property that is not static. The constructor must set every property that has no default, on every path. If it does not, the program does not compile.
You write a constant as visibility const type NAME = value;, for example public const uint WIDTH = 5;. Reading Limits::WIDTH gives a uint, the type you wrote.
Good to know: the compiler works out a default value once, before the program runs. So it must be a value written directly in the code, an enum case, a class constant, or an array of these. Code that computes a value belongs in the constructor.
The examples below show defaults and a constructor, constants and a static property, and a small retry policy. Example 04 shows a computed default, which does not compile. Example 05 shows constants that contain enum cases.
A slot every object has
<?nvs// A property is a variable with a type that belongs to an object.// A property with a default value is set when the object is created.// The constructor must set every other property, or the program does not compile.
class Ticket{ public string $subject; public string $status = 'open'; public array<string> $labels = []; public ?string $assignee = null;
public function constructor(string $subject) { $this->subject = $subject; }}
Ticket $first = new Ticket('printer is jammed');
echo $first->subject, ' [', $first->status, "]\n";echo 'labels: ', Core\Arr::count($first->labels), ', assignee: ', $first->assignee ?? 'nobody', "\n";
// Each object has its own properties. Changing `$second` does not change `$first`.Ticket $second = new Ticket('badge reader is offline');$second->status = 'waiting';$second->labels = ['hardware'];$second->assignee = 'Ada';
echo $second->subject, ' [', $second->status, '] ', Core\Str::join($second->labels, ', '), ' -> ', $second->assignee ?? 'nobody', "\n";echo $first->subject, ' [', $first->status, "]\n";printer is jammed [open]labels: 0, assignee: nobodybadge reader is offline [waiting] hardware -> Adaprinter is jammed [open]Names that never change
<?nvs// A constant is a value that is fixed before the program runs. You declare it with a type.// Reading the constant gives a value of exactly that type.// So you can use it wherever that type is needed, also as a property's default value.
class Limits{ public const uint ATTEMPTS = 3; public const string QUEUE = 'outbound'; public const float BACKOFF = 1.5;}
class Delivery{ public uint $left = Limits::ATTEMPTS; public string $queue = Limits::QUEUE; public static uint $made = 0;
public function constructor() { Delivery::$made = Delivery::$made + 1; }}
echo 'queue ', Limits::QUEUE, ', up to ', Limits::ATTEMPTS, ' attempts, backing off by ', Limits::BACKOFF, "\n";
Delivery $one = new Delivery();Delivery $two = new Delivery();$two->left = $two->left - 1;
echo 'first has ', $one->left, ' attempts left, second has ', $two->left, "\n";
// A static property belongs to the class, not to one object.// Both constructors added 1 to the same `Delivery::$made`, so this prints `2`.echo 'deliveries made: ', Delivery::$made, "\n";queue outbound, up to 3 attempts, backing off by 1.5first has 3 attempts left, second has 2deliveries made: 2A retry policy in one place
<?nvs// This job retries a failed task. The rules for every job are constants in `Policy`.// The state of one job is in the properties of `Job`, so each job has its own.// The constructor must set every property that has no default value.
class Policy{ public const uint ATTEMPTS = 3; public const uint TIMEOUT_MS = 250; public const string DEAD_LETTER = 'parked';}
class Job{ public string $name; public uint $attempt = 1; public string $state = 'ready'; public ?string $lastError = null;
public function constructor(string $name) { $this->name = $name; }
public function fail(string $reason): void { $this->lastError = $reason;
if ($this->attempt < Policy::ATTEMPTS) { $this->attempt = $this->attempt + 1; $this->state = 'ready';
return; }
$this->state = Policy::DEAD_LETTER; }}
Job $job = new Job('send-invoice');
echo $job->name, ': ', $job->state, ', attempt ', $job->attempt, ' of ', Policy::ATTEMPTS, "\n";
array<string> $failures = ['timed out', 'timed out', 'connection refused'];
foreach ($failures as string $reason) { $job->fail($reason); echo "after \"", $reason, "\": ", $job->state, ', attempt ', $job->attempt, "\n";}
echo 'last error: ', $job->lastError ?? 'none', ', giving up after ', Policy::TIMEOUT_MS, "ms per try\n";send-invoice: ready, attempt 1 of 3after "timed out": ready, attempt 2after "timed out": ready, attempt 3after "connection refused": parked, attempt 3last error: connection refused, giving up after 250ms per tryA default that is computed
<?nvs// Shows that a property's default value must be known before the program runs.// `Core\Math::abs(-5)` is a call, so this program does not compile.// proof: compile-error
class Retry{ public int $delay = Core\Math::abs(-5);}
Retry $retry = new Retry();echo $retry->delay, "\n";error[E0472]: a property default must be a `int` constant --> 04-a-default-that-is-computed.nvs:8:25 |8 | public int $delay = Core\Math::abs(-5); | ^^^^^^^^^^^^^^^^^^ not a constant of the declared type = help: a property default is computed once, when the program compiles, and copied into every new object. Write a value such as `0` or `'text'`, an enum case, another class's `const`, `Foo::class` or an array of these. Set any other value in `constructor`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.A table of enum cases
<?nvs// Shows class constants and a property default that contain enum cases, alone and inside arrays.
enum Priority { Low, Normal, Urgent }
class Support{ // This constant is an array. Its keys are the cases of `Priority`. public const array<Priority, string> LABELS = [ Priority::Low => 'low', Priority::Normal => 'normal', Priority::Urgent => 'urgent', ];
// A list of cases, in the order the team works on them. public const array<Priority> ORDER = [Priority::Urgent, Priority::Normal, Priority::Low];
// A property default may also contain cases. Each object gets its own copy. public array<Priority> $muted = [Priority::Low];}
// This prints `urgent`, then `normal`, then `low`.foreach (Support::ORDER as Priority $priority) { echo Support::LABELS[$priority], "\n";}
Support $desk = new Support();$desk->muted[] = Priority::Normal;
// `$muted` now has two cases. This prints `2 muted, the first is low`.echo Core\Arr::count($desk->muted), ' muted, the first is ', Support::LABELS[$desk->muted[0]], "\n";urgentnormallow2 muted, the first is lowDetails
A property needs a type. public $x = 1; is a syntax error (E0101).
A default must be a constant of the property's type. That is a value written in the code, also with a minus sign such as -3. It can also be an enum case, a class constant such as Limits::ATTEMPTS or self::ATTEMPTS, or an array of these, such as [Priority::Low, Priority::High]. A union type takes any value one of its members takes: ?string $label = null, ?string $label = "plain" and "read"|"write" $mode = "read" all compile. Any other default does not compile (E0472). That includes a call, null for a string property, and "delete" for a "read"|"write" property.
A property with no default must be set on every path out of the constructor. A constructor that sets it only inside an if does not compile (E0409). A static property has no constructor to set it. It needs a default or a nullable type, and a nullable one starts as null. Without either, it is E0409 too.
A constant needs a type. public const W = 5; does not compile (E0246). Reading a constant gives its declared type exactly. With public const uint WIDTH = 5;, int $i = Limits::WIDTH; does not compile (E0401).
The compiler copies a constant's value into every place that reads it. So the value must be known when the program compiles. These values work, alone or inside an array, as a value or as a key: a number, a string, a bool, an enum case, Priority::High as int, Foo::class, and another class's constant whose value is a number or a string. A property default can contain the same values.
Some constants compile, but a read of one does not compile (E0792). That is the case for self::B + 1 and "a" . "b". It is also the case for another class's constant whose value is an array or an enum case. Write that array or case out in your own constant.
readonly, lateinit and static
A property is a named value that each object of a class has.
Every property declares its type and its visibility. A property without a default value must be assigned in the constructor, on every path out of it. A default value must be a constant: a number, a string, a bool, an enum case, a class constant, [] or null.
Three keywords change when a property gets its value. readonly means the constructor sets it once and no later code can change it. lateinit means another part of the program sets it after new returns. Reading it before that first write throws an error. static means there is one value for the whole class, and it starts every request at the value you declared.
The examples below show defaults, a constructor, readonly, static and lateinit. Others show a constructor that does not compile, a lateinit read that throws, isinit, a readonly write and static:: on a property.
Defaults and a constructor
<?nvs// Shows the two ways a property gets its first value: a default written in the// class, or an assignment in the constructor.
class Invoice{ // These three have a default, so the constructor does not touch them. public string $currency = 'EUR'; public int $total = 0; public array<string> $lines = [];
// This one has no default. The constructor must give it a value. public string $customer;
public function constructor(string $customer) { $this->customer = $customer; }
public function add(string $line, int $amount): void { $this->lines[] = $line; $this->total = $this->total + $amount; }}
var $invoice = new Invoice('Ada Lovelace');$invoice->add('Keyboard', 4900);$invoice->add('Cable', 900);
// This prints: Ada Lovelace owes 5800 EUR for 2 lines.echo $invoice->customer, ' owes ', $invoice->total, ' ', $invoice->currency;echo ' for ', Core\Arr::count($invoice->lines), " lines.\n";Ada Lovelace owes 5800 EUR for 2 lines.Readonly values that never change
<?nvs// Shows `readonly`. The constructor gives each property its value, and no other// code can change it.
final class Money{ public function constructor(public readonly int $cents, public readonly string $currency) {}
// The two amounts cannot change, so adding them returns a third object. public function plus(Money $other): Money { return new Money($this->cents + $other->cents, $this->currency); }}
var $coffee = new Money(350, 'EUR');var $cake = new Money(425, 'EUR');var $order = $coffee->plus($cake);
// This prints 350 + 425 = 775 EUR. The first two objects still have their own// values.echo $coffee->cents, ' + ', $cake->cents, ' = ', $order->cents, ' ', $order->currency, "\n";350 + 425 = 775 EURA shared counter and a logger attached later
<?nvs// Shows a `static` property, which belongs to the class itself, and a `lateinit`// property, which is written after the object is created.
class Printer{ public function write(int $number, string $subject): void { echo '#', $number, ' ', $subject, "\n"; }}
class Ticket{ // One value for the whole class. Every request starts it again at 0. public static int $issued = 0;
// The printer is chosen elsewhere, so it arrives after `new` returns. public lateinit Printer $printer;
public readonly int $number;
public function constructor(public string $subject) { self::$issued = self::$issued + 1; $this->number = self::$issued; }
// A class may read its own `lateinit` property once a write came first on // the same path. This method does both. public function printWith(Printer $printer): void { $this->printer = $printer; $this->printer->write($this->number, $this->subject); }}
var $printer = new Printer();
var $first = new Ticket('The printer is out of paper');$first->printWith($printer);
var $second = new Ticket('A new keyboard');$second->printWith($printer);
// This prints 2. The counter belongs to the class, so both tickets added to it.echo 'tickets so far: ', Ticket::$issued, "\n";#1 The printer is out of paper#2 A new keyboardtickets so far: 2A property not set on every path
<?nvs// Shows a constructor that sets `$n` only when `$big` is true. The other path// leaves it with no value, so this program does not compile.// proof: compile-error
class Box{ public int $n;
public function constructor(bool $big) { if ($big) { $this->n = 10; } }}error[E0409]: `$n` is not assigned on every path out of the constructor --> 04-a-property-not-set-on-every-path.nvs:8:16 | 8 | public int $n; | ^^ declared here...10 | public function constructor(bool $big) | ----------- not assigned along every path out of this constructor
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Each kind of default
<?nvs// Shows the values a property default may have: an enum case, a class// constant, an empty array and `null`.
enum Mode { Off, On }
class Config{ public const int DEFAULT_SIZE = 8; public Mode $mode = Mode::On; public int $size = self::DEFAULT_SIZE; public array<int> $ports = []; public ?string $label = null;}
var $c = new Config();
// This prints `1 8 0 none`. `Mode::On` is the second case, so its number is 1.echo $c->mode as int, ' ', $c->size, ' ', Core\Arr::count($c->ports), ' ', $c->label ?? 'none', "\n";1 8 0 noneReading lateinit too early
<?nvs// Shows what happens when code reads a `lateinit` property before it has a// value. The read throws a `LogicError`.
class Logger{ public function name(): string { return 'log'; }}
class Widget{ public lateinit Logger $logger;
public function attach(Logger $l): void { $this->logger = $l; }}
var $w = new Widget();
// Nothing has set `$logger` yet, so this prints the error message.try { echo $w->logger->name(), "\n";} catch (Throwable $e) { echo 'threw: ', $e->message, "\n";}
// After `attach`, the read works. This prints `log`.$w->attach(new Logger());echo $w->logger->name(), "\n";threw: `Widget`'s property `$logger` is read before it is initializedlogIsinit checks for a value
<?nvs// Shows `isinit`. It returns `true` when a `lateinit` property has a value.// It does not read the property, so it never throws.
class Post{ public lateinit ?string $note;}
var $p = new Post();
// This prints `no`.echo isinit($p->note) ? 'yes' : 'no', "\n";
// `null` is a value too. This prints `yes`.$p->note = null;echo isinit($p->note) ? 'yes' : 'no', "\n";noyesA readonly write after new
<?nvs// Shows that only the constructor may write a `readonly` property. This// program writes it after `new`, so it does not compile.// proof: compile-error
class Id{ public function constructor(public readonly int $value) {}}
var $id = new Id(1);$id->value = 2;error[E0782]: `Id::$value` is `readonly`, so only `Id`'s constructor writes it --> 08-a-readonly-write-after-new.nvs:13:1 |13 | $id->value = 2; | ^^^^^^^^^^ this write happens after construction = help: a `readonly` property is assigned once, in the constructor. Assign it there, or make it a constructor parameter (`public readonly T $x`). If the property must change, remove `readonly`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Static on a static property
<?nvs// Shows that `static::$n` does not compile. Write `self::$n` or `Counter::$n`// to read a `static` property.// proof: compile-error
class Counter{ public static int $n = 0;
public static function read(): int { return static::$n; }}error[E0499]: `static::` does not resolve a static property --> 09-static-on-a-static-property.nvs:12:16 |12 | return static::$n; | ^^^^^^ the called class is only known at run time = help: write `self::` for the class this is declared in, or name the class whose storage is meant
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
Only a plain = assigns a property in the constructor. $this->n += 1; reads the property first, so a constructor with only that line is the error E0409. A ?T property with no default and no assignment starts as null.
A return in a constructor has no value. return 1; is the error E0248. A bare return; leaves the constructor early, and every property must already have its value on that path. If one does not, it is E0409.
A lateinit property may have any type, and a default too. If a method reads it before any write on the same path, the read does not compile (E0428). Any other read with no value first throws a LogicError when it runs. Example 06 prints its message. isinit works only on a lateinit property. On any other property it is the error E0853. A property cannot be both lateinit and readonly (E0427).
A readonly property has no default, and that includes a static readonly one (E0249). Every write after the constructor is the error E0782: =, a compound operator such as +=, and an append with []. A write in another method of the class is E0782 too, and so is a write in a subclass constructor after parent::constructor(). A second write on the same path through the constructor is E0782 as well. unset($a->v) is the error E0413 for every declared property.
A static property with no default and a type that is not nullable is the error E0409. A subclass shares the same value with its parent: B::$n = 5; also changes A::$n. static::$n is the error E0499. Write self::$n or the class name. ++, -- and every compound operator work on a static property. An unknown one is the error E0309, and a private one read outside its class is E0471.
LateInit
A lateinit property can get its value the first time a program reads it. The class implements the interface LateInit and writes one method, initProperty.
When a read finds a lateinit property with no value, Novis 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. A write to one element, such as $post->tags[] = "news", calls the method first too.
If initProperty returns and the property still has no value, the read throws a LogicError. If the method throws an error, the property still has no value, and the next read calls the method again.
Good to know: the write that gives the property its first value inside initProperty does not run a set hook, PropertyGuard or PropertyObserver. A second task that reads the property while the method runs waits until it returns. A rename of the property also renames the string that initProperty compares.
The examples below show a property set on the first read, one method for several properties, a second try after an error, and the error when a property stays empty.
Loading on the first read
<?nvs// Shows a property that gets its value on the first read. `Post` loads its// author only when the program reads `$author`.
class Author{ public function constructor(public string $name) {}}
class Post implements LateInit{ public lateinit Author $author;
public function constructor(public string $title) {}
// Novis calls this method with the name of the property that has no value. public function initProperty(string $name): void { echo "loading the author\n"; $this->author = new Author('Ada'); }}
var $post = new Post('Hello');echo $post->title, "\n";
// The first read calls `initProperty`. The second read does not.echo $post->author->name, "\n";echo $post->author->name, "\n";Helloloading the authorAdaAdaOne method for every property
<?nvs// Shows one `initProperty` method that sets several properties of different// types. The method tests `$name` to know which property to set.
class Page implements LateInit{ public lateinit int $views; public lateinit array<string> $tags; public lateinit ?string $note;
public function initProperty(string $name): void { echo 'init ', $name, "\n"; if ($name == 'views') { $this->views = 0; } elseif ($name == 'tags') { $this->tags = ['news']; } else { $this->note = null; } }}
var $page = new Page();
// `isinit` tests the property without reading it, so it calls nothing.echo isinit($page->views) ? 'set' : 'not set', "\n";echo $page->views, "\n";echo isinit($page->views) ? 'set' : 'not set', "\n";
// A write to one element calls `initProperty` first, then adds the element.$page->tags[] = 'tech';echo Core\Json::encode($page->tags), "\n";
// `null` is a value too, so this read calls `initProperty` only once.echo $page->note ?? 'no note', "\n";echo $page->note ?? 'no note', "\n";not setinit views0setinit tags["news","tech"]init noteno noteno noteTrying again after an error
<?nvs// Shows what happens when `initProperty` throws an error. The property still// has no value, so the next read calls `initProperty` again.
class Settings implements LateInit{ public lateinit string $theme; public int $tries = 0;
public function initProperty(string $name): void { $this->tries = $this->tries + 1; // The first try fails, for example because a server did not answer. if ($this->tries == 1) { throw new RuntimeError('the settings server did not answer'); } $this->theme = 'dark'; }}
var $settings = new Settings();try { echo $settings->theme, "\n";} catch (RuntimeError $e) { echo 'error: ', $e->message, "\n";}
// This read calls `initProperty` a second time, and it works.echo $settings->theme, "\n";echo 'tries: ', $settings->tries, "\n";error: the settings server did not answerdarktries: 2A property that stays empty
<?nvs// Shows the error when `initProperty` returns and the property still has no// value. `Post` sets `$author` but not `$views`.
class Author{ public function constructor(public string $name) {}}
class Post implements LateInit{ public lateinit Author $author; public lateinit int $views;
public function initProperty(string $name): void { echo 'initProperty ', $name, "\n"; if ($name == 'author') { $this->author = new Author('Ada'); } }}
var $p = new Post();echo $p->author->name, "\n";echo $p->author->name, "\n";
// This read calls `initProperty`, and then throws a `LogicError`.try { echo $p->views, "\n";} catch (LogicError $e) { echo $e->message, "\n";}initProperty authorAdaAdainitProperty views`initProperty` returned, but `$views` is still not initialized.Details
In a class that implements LateInit, a method may read a lateinit property before any write. This compiles, even in the constructor, because the read calls initProperty. In a class without LateInit, the same read in the constructor is the error E0428. A class that implements LateInit and has no initProperty method is the error E0449.
initProperty runs only for a lateinit property with no value. A read of a plain property never calls it. A write before the first read gives the property its value, so a later read does not call initProperty. isinit($p->views) tests the property and calls nothing. A compound assignment such as $p->views += 1 reads first, so it calls initProperty and then adds 1.
initProperty may set more properties than the one it was called for. A later read of another property it set does not call it again. A lateinit property that a subclass declares calls the parent's initProperty too, with the subclass property's name.
Example 04 shows the message of the LogicError when initProperty returns and the property still has no value. A read of a property $v inside its own initProperty call throws a LogicError too. Its message is ` $v is read while initProperty initializes it. `
Inside initProperty, only the first write of a property is plain. A second write of the same property in the method runs PropertyGuard, a set hook and PropertyObserver, as every other write does.
The reference page of LateInit has one more example.
A child class can use covariant to declare a parent’s property again with a narrower type.
Do and don’t
Section titled “Do and don’t”- Do give every property a type and, where you can, a default.
- Do use
readonlyfor a value that must not change after the object is created. - Don’t use
lateinitto skip setting a property in the constructor. Use it only when the value is not known until later. - Don’t use a
staticproperty to keep data between requests. Every request starts with the default.
