Working with objects
A variable that contains an object points to it. Assigning the variable, passing it to a method, or storing it in an array does not copy the object. Novis frees an object when nothing points to it.
Objects are shared
An object is never copied when your program passes it from one place to another. A variable, a property, an array element and a parameter all hold a reference to the object. Assigning it to a second variable gives that variable the same object. Passing it to a function gives the function the same object. A write through any one of them is seen through all of them.
== on two objects of your own class tests whether they are the same object. Two separate objects are never equal, even when every property in them has the same value. Six Core\Time classes, such as Date and Duration, are the exception: == compares their value.
clone makes a new object of the same class and copies every property into it. The copy is one level deep. An array property is copied, so the two objects have two arrays. An object property is shared, so both objects point at the same inner object. No method runs during a clone.
The examples below show two variables naming one object, a function that changes the object it is given, and a copy that is edited without changing the original.
Two names for one object
<?nvs// Shows what happens when you assign an object to a second variable. Both// variables name the same object, so a write through one is read through the other.
class Counter{ public int $value = 0;}
var $counter = new Counter();var $alias = $counter;
// The write goes through `$alias`. Both variables name one object, so this prints `5|5`.$alias->value = 5;echo $counter->value, '|', $alias->value, "\n";
// `==` on two objects is true when they are the same object. This prints `1`.echo ($counter == $alias) as string, "\n";
// A second `new` makes a second object. It has the same value and is still a// different object, so `==` is false and `as string` prints an empty string.var $other = new Counter();$other->value = 5;echo ($counter == $other) as string, "|done\n";5|51|doneA function changes the object it is given
<?nvs// Shows that a function receives the caller's object and not a copy. The same// object is also kept in an array and in a property. All of them read one object.
class Order{ public int $total = 0;
public function constructor(public string $customer) {}}
class Invoice{ public function constructor(public Order $order) {}}
class Discount{ // The parameter holds the caller's object, so this write changes it. public static function applyTo(Order $order, int $off): void { $order->total = $order->total - $off; }}
var $order = new Order('Ada');$order->total = 100;
// One object, now named in three places: a variable, an array element and a property.array<Order> $open = [$order];var $invoice = new Invoice($order);
Discount::applyTo($order, 25);
// All three read the one object, so this prints `75|75|75`.echo $order->total, '|', $open[0]->total, '|', $invoice->order->total, "\n";
// The array element is the same object, so this second call changes it too.// This prints `70|70|70`.Discount::applyTo($open[0], 5);echo $order->total, '|', $open[0]->total, '|', $invoice->order->total, "\n";75|75|7570|70|70A draft copy of a saved record
<?nvs// Shows how `clone` makes a copy you can edit without changing the original.// A program does this when it prepares a draft of a record it already saved.
class Address{ public function constructor(public string $city) {}}
class Profile{ public array<string> $tags = [];
public function constructor(public string $name, public Address $address) {}}
var $saved = new Profile('Ada', new Address('Berlin'));$saved->tags[] = 'customer';
var $draft = clone $saved;
// `name` and `tags` are copied into the draft. These writes change the draft only.$draft->name = 'Ada Lovelace';$draft->tags[] = 'draft';echo $saved->name, '|', $draft->name, "\n";echo Core\Arr::count($saved->tags), '|', Core\Arr::count($draft->tags), "\n";
// `address` holds an object. The copy shares that object, so this write is read// through both profiles. It prints `Vienna|Vienna`.$draft->address->city = 'Vienna';echo $saved->address->city, '|', $draft->address->city, "\n";
// Give the draft its own `Address` when you want the two to differ.$draft->address = new Address('Berlin');echo $saved->address->city, '|', $draft->address->city, "\n";Ada|Ada Lovelace1|2Vienna|ViennaVienna|BerlinDetails
clone keeps the class of the object. If a variable of type Animal has a Dog, its clone is a Dog too. A private constructor does not stop clone, because no constructor runs.
An array property is copied, but an object inside the array is not. After a clone, both arrays contain the same objects. A write to $copy->items[0]->price is seen through the original too.
!= on two objects is true when they are different objects. == on objects of two classes that are not related is the error E0466. == with null tests whether a ?Note variable has an object.
Objects that can be null
?Box is a type that holds a Box or null. A plain Box never holds null, so a value of that type is always there.
-> on a value that may be null does not compile. Novis needs you to say what should happen when the value is missing, and there are two ways to say it.
Write ?->. On a null value the whole access returns null. The method is not called and its arguments are not evaluated. Put ?? "something" after it to give the missing case a value.
Test the value first. Inside if ($box != null) the value is no longer nullable, so plain -> works there. This is the better choice when the branch does several things with the value.
The examples below show reading a setting that may be missing, testing a value before using it, a chain of accesses where any step may be absent, and a -> that does not compile.
Reading a value that may be missing
<?nvs// Shows how to read from a value that may be `null`. `?->` returns `null` when// the value is missing, and `??` gives you something to use instead.
class Theme{ public function constructor(public string $name) {}}
?Theme $chosen = new Theme('dark');?Theme $missing = null;
// `$chosen` holds a `Theme`, so `?->` reads the property. This prints `dark`.echo $chosen?->name ?? 'default', "\n";
// `$missing` is `null`, so the whole access is `null` and `??` takes over.// This prints `default`.echo $missing?->name ?? 'default', "\n";
// Without `??` the result is `null` itself. `as string` prints an empty text for it.?string $name = $missing?->name;echo '[', $name as string, "]\n";darkdefault[]Testing for null before using a value
<?nvs// Shows the second way to use a value that may be `null`. Inside `if ($x != null)`// the value is no longer nullable, so plain `->` works for the whole branch.
class Session{ public function constructor(public string $user, public int $minutes) {}
public function isFresh(): bool { return $this->minutes < 30; }}
class Greeting{ public static function forSession(?Session $session): string { if ($session != null) { // Three uses of the value, and none of them needs `?->`. if ($session->isFresh()) { return 'Welcome back, ' . $session->user; } return 'Please sign in again, ' . $session->user; } return 'Hello, guest'; }}
// This prints one line for each case.echo Greeting::forSession(new Session('ada', 5)), "\n";echo Greeting::forSession(new Session('ada', 90)), "\n";echo Greeting::forSession(null), "\n";Welcome back, adaPlease sign in again, adaHello, guestA chain where any step may be absent
<?nvs// Shows a chain of accesses where any step may be missing. A shipping label// needs the country of a customer's address, and a customer may have neither.
class Country{ public function constructor(public string $code) {}}
class Address{ public function constructor(public string $city, public ?Country $country) {}}
class Customer{ public function constructor(public string $name, public ?Address $address) {}
public function shippingCountry(): string { // Each `?->` stops the chain at the first missing step. One `??` at the // end covers every one of them. return $this->address?->country?->code ?? 'unknown'; }}
array<Customer> $customers = [ new Customer('Ada', new Address('Berlin', new Country('DE'))), new Customer('Grace', new Address('Vienna', null)), new Customer('Alan', null),];
// This prints `DE`, then `unknown` twice.foreach ($customers as Customer $customer) { echo $customer->name, ': ', $customer->shippingCountry(), "\n";}Ada: DEGrace: unknownAlan: unknownArrow on a value that may be null
<?nvs// Shows that `->` does not compile on a value that may be `null`.// `$none` is a `?Box`, so the read below is an error.// proof: compile-error
class Box{ public int $count = 1;}
?Box $none = null;echo $none->count, "\n";error[E0459]: `null|Box` may be `null`, so `->` cannot reach a member of it --> 04-arrow-on-a-value-that-may-be-null.nvs:12:6 |12 | echo $none->count, "\n"; | ^^^^^ this receiver is nullable = help: test it first — inside `if ($x != null) { … }` the receiver is no longer nullable — or use `?->`, which answers `null` instead of reaching the member
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
-> on a value that may be null is the error E0459. This is true for a property and for a method call.
The result of ?-> can be null. $box?->count on an int property is a ?int. Assigning it to an int variable is the error E0401. Write $box?->count ?? 0 to get an int.
Each ?-> covers one step of a chain. In $box?->inner()->label, the result of ?->inner() can be null, so the -> after it is E0459. This is true even when inner() returns a Box. Write ?-> for every step after the first one: $box?->inner()?->label.
$box?->save(); can call a void method as a statement. When $box is null, nothing runs. isset($box?->count) is false when $box is null.
The object type
object is a type that contains an object of any class. It names no class itself. The compiler only checks that the value is an object. Use it where a value may come from several unrelated classes, such as a plugin a program loaded.
A property read through an object compiles. The name is looked up while the program runs. The read throws an error when the object has no property with that name.
A method call through an object does not compile. Name the class first. Inside if ($value is Tag), you can call the methods of Tag. $value as Tag gives you a Tag to use anywhere.
The examples below show a value of unknown class, a check before calling a method on it, a list of mixed objects sorted by class, and a method call that does not compile.
A value whose class is not known
<?nvs// Shows what you can do with a value typed `object`. It holds an object of any// class, so a property read works and a method call needs a class name first.
class Tag{ public function constructor(public string $text) {}}
class Label{ public function constructor(public string $text) {}}
class Pick{ public static function first(): object { return new Tag('red'); }
public static function second(): object { return new Label('blue'); }}
object $one = Pick::first();object $two = Pick::second();
// Both classes happen to have a property called `text`. The name is looked up// while the program runs, so this prints `red|blue`.echo $one->text as string, '|', $two->text as string, "\n";
// `as Tag` converts the value to a `Tag`. The result is an ordinary `Tag`.Tag $tag = $one as Tag;echo $tag->text, "\n";red|blueredChecking the class before calling a method
<?nvs// Shows how to call a method on a value typed `object`. `is` tests the class,// and inside that branch the call compiles.
class Duck{ public function speak(): string { return 'quack'; }}
class Robot{ public function beep(): string { return 'beep'; }}
class Voice{ public static function of(object $thing): string { // Each branch narrows the value to one class. Inside the branch, you can // call the methods of that class. if ($thing is Duck) { return $thing->speak(); } if ($thing is Robot) { return $thing->beep(); } return 'silence'; }}
class Stone{}
// This prints one line for each value.echo Voice::of(new Duck()), "\n";echo Voice::of(new Robot()), "\n";echo Voice::of(new Stone()), "\n";quackbeepsilenceSorting a mixed list of objects
<?nvs// Shows a list holding objects of several unrelated classes. A program does this// when it receives events from different sources and handles each kind its own way.
class Payment{ public function constructor(public int $cents) {}}
class Refund{ public function constructor(public int $cents) {}}
class Note{ public function constructor(public string $text) {}}
class Ledger{ public static function balance(array<object> $events): int { int $total = 0; foreach ($events as object $event) { if ($event is Payment) { $total = $total + $event->cents; } if ($event is Refund) { $total = $total - $event->cents; } // A `Note` changes no amount, so it is left out of the total. } return $total; }}
array<object> $events = [ new Payment(1200), new Note('customer called'), new Refund(200), new Payment(50),];
// This prints `1050`.echo Ledger::balance($events), "\n";1050A method call through object
<?nvs// Shows that a method call through `object` does not compile. Test the class// with `is` first, or convert the value with `as`.// proof: compile-error
class Tag{ public function shout(): string { return 'TAG'; }}
object $o = new Tag();echo $o->shout(), "\n";error[E0477]: `object` names no class, so it has no method `shout` --> 04-a-method-call-through-object.nvs:15:6 |15 | echo $o->shout(), "\n"; | ^^^^^^^^^ called on a receiver that names no class here = help: test the receiver for the class that declares `shout` first: `if ($x is ClassName) { … }`. An `object` has no methods of its own
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A method call through object is the error E0477. This is true for ?-> on a ?object too.
An object variable contains only an object of a class. An int, null or an anonymous function at an object is the error E0401. Write ?object for a value that can be null.
An object value at a parameter or a variable of a class type is the error E0401. Convert it with as first.
A property read through object gives mixed. So int $n = $o->count; is the error E0401. Write $o->count as int.
A write through object compiles, and the value is checked while the program runs. A property the object does not have throws a RuntimeError. A value of another type than the property's throws a RuntimeError too, and so does a write to a readonly property.
callable, class and shape types
Types for a function value, a class, any object, and an object described by its fields.
A callable is an anonymous function written with fn, or a method reference such as Core\Str::length. A class, interface or enum name is a type, and object is the type every instance fits. A shape describes an object by its fields. as Point checks that a value has those fields and throws an error if not. is Point gives true or false.
Where a class<T> is expected, write the class as Invoice::class. A class name in a string needs as class<T>, and is checked when the program runs. as ?class<T> gives null for a wrong name. new $c() throws a LogicError when the class is abstract or an interface.
Good to know: a call through a callable returns a mixed value, so convert the result where you use it: $f(4) as int.
The examples below pass a pricing rule around, check a value against a shape, and pick a report class from a name. Then they read the class of an object, show a shape without a name as a compile error, and pass a class to a function.
Pass a pricing rule around
<?nvs// A discount rule written once and then handed around like any other value.// A `callable` is an anonymous function or a method reference. A call through one// returns `mixed`, so the code says the type of the result where it is used.
callable $tenPercentOff = fn(int $cents): int => $cents - Core\Math::quotient($cents, 10);
class Till{ public static function apply(callable $rule, array<int> $prices): int { int $total = 0; foreach ($prices as int $price) { int $charged = $rule($price) as int; $total = $total + $charged; } return $total; }}
array<int> $basket = [1000, 2500];echo Till::apply($tenPercentOff, $basket), "\n";echo $tenPercentOff(500) as int, "\n";3150450Describe a value by the fields it has
<?nvs// A point on a map, described by the fields it has and not by a class.// A shape needs a name to be written in front of a variable, so it gets one with `type`.
type Point = { x: int, y: int };
class Grid{ public static function describe(Point $p): string { return '(' . ($p->x as string) . ', ' . ($p->y as string) . ')'; }}
// A value with more fields than the shape asks for still fits it.Point $home = { x: 3, y: 4 };var $pin = { x: 10, y: 20, label: 'office' };
echo Grid::describe($home), "\n";echo Grid::describe($pin), ' ', $pin->label, "\n";
// A call through a `callable` returns a `mixed` value.callable $findPlace = fn(string $name): mixed => $name == 'depot' ? { x: 7, y: 1 } : { city: $name };
// `as Point` checks that the value has an `int` field `x` and an `int` field `y`.// If a field is missing, it throws an error. The second call shows this.echo Grid::describe($findPlace('depot') as Point), "\n";
try { echo Grid::describe($findPlace('Vienna') as Point), "\n";} catch (RuntimeError $e) { echo $e->message, "\n";}
// `is Point` does the same check and gives `true` or `false`, so nothing is thrown.mixed $place = $findPlace('Vienna');echo $place is Point ? Grid::describe($place) : 'not on the grid', "\n";(3, 4)(10, 20) office(7, 1)cannot convert a value of another type to `{ x: int, y: int }`not on the gridPick the report format from a setting
<?nvs// Picks a report format from a setting. The setting is text, and the program needs a class.// `as class<Renders>` converts a class name to a class reference.// The program uses the reference to create the report and to call the static method `extension`.
interface Renders{ public function render(array<string> $rows): string; public static function extension(): string;}
class CsvReport implements Renders{ public function render(array<string> $rows): string { return Core\Str::join($rows, ','); }
public static function extension(): string { return 'csv'; }}
class LinesReport implements Renders{ public function render(array<string> $rows): string { return Core\Str::join($rows, "\n"); }
public static function extension(): string { return 'txt'; }}
array<string> $rows = ['north', 'south'];
// `CsvReport::class` is a class reference, and it is checked when the program compiles.// If `CsvReport` did not implement `Renders`, the program would not compile.class<Renders> $default = CsvReport::class;
// A name from a setting is checked when the program runs. `as ?class<Renders>` gives `null`// for a name that is not a `Renders` class. Then `??` uses the default format.array<string> $settings = ['LinesReport', 'PdfReport'];
foreach ($settings as string $setting) { class<Renders> $format = ($setting as ?class<Renders>) ?? $default; Renders $report = new $format();
echo $setting, ' writes a .', $format::extension(), " file:\n"; echo $report->render($rows), "\n";}LinesReport writes a .txt file:northsouthPdfReport writes a .csv file:north,southAny object and its class
<?nvs// Shows an `object` variable, and how `is` and `as` get its class back.
class Cell{ public int $n = 1;}
class Row{ public int $n = 2;}
// Any instance can be assigned to `object`. Reading `$o->n` gives a `mixed` value.object $o = new Cell();echo $o->n, "\n";
// `is Cell` tests the class. `as Cell` converts to it, so `->n` is an `int`. This prints `cell 1`.echo ($o is Cell) ? 'cell' : 'other', ' ', ($o as Cell)->n, "\n";
// The object is not a `Row`, so `as Row` throws an error.try { echo ($o as Row)->n, "\n";} catch (RuntimeError $e) { echo $e->message, "\n";}1cell 1cannot convert a value of another type to `Row`A shape needs a name
<?nvs// Shows that a shape needs a name before a variable can have it. A `{` at the start of// a statement opens a block, so this program does not compile.// proof: compile-error
{ x: int, y: int } $p = { x: 1, y: 2 };error[E0134]: a local declaration cannot be typed with a bare shape --> 05-a-shape-needs-a-name.nvs:6:1 |6 | { x: int, y: int } $p = { x: 1, y: 2 }; | ^^^^^^^^^^^^^^^^^^ `{` at the start of a statement already opens a block = help: give the shape a name first: `type Point = { x: int }; Point $point;`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Pass a class to a function
<?nvs// Shows a function that takes a class as its argument, and a call that passes `Invoice::class`.
interface Storable{ public static function table(): string;}
class Invoice implements Storable{ public static function table(): string { return 'invoices'; }}
class Store{ // `$c` is a class, not an object. The class implements `Storable`. `$c::table()` calls its static method. public static function describe(class<Storable> $c): string { return 'rows go to the table ' . $c::table(); }}
// `Invoice::class` is a class reference, so the call needs no `as`. This prints:// rows go to the table invoicesecho Store::describe(Invoice::class), "\n";rows go to the table invoicesDetails
A string is never a callable. callable $f = "strlen"; is the error E0418. Write a method reference such as Core\Str::length instead.
Any class instance can be assigned to an object variable. You can read a property through it by name, and the result is mixed. A property the object does not have throws a RuntimeError. $o is Cell tests the class, and $o as Cell converts to it. If the object is another class, as throws a RuntimeError. as ?Cell is the error E0473, so use is to test first.
A class<T> variable contains a class, not an instance. T is a class or an interface, and every class in the variable is T or extends or implements it. A class<Dog> can be assigned to a class<Animal>. Two class references are equal when they are the same class.
There are two ways to get a class reference. Where a class<T> is expected, Dog::class is a class reference. That place can be a variable, a parameter, a return value or a default value. self::class, parent::class, static::class and $obj::class work the same way. The compiler checks the class. A class that is not T and does not extend or implement T is the error E0708. Everywhere else, Dog::class is a string, the class name.
The other way is as class<T>, for a class name in a string. A class name in quotes is checked when the program compiles. A name in a variable is checked when the program runs. A wrong name throws a RuntimeError, and as ?class<T> gives null for it. A string where a class<T> is expected does not compile. The error message shows how to write the as. $cls as string gives the class name.
Only three places take a class reference: new $cls(), $cls::f() and $x is $cls. A string in any of the three is the error E0496. Comparing a string with a class<T> is the error E0466.
A shape cannot be written in front of a variable, because a { at the start of a statement opens a block. { x: int } $p = …; is the error E0134. Name the shape with type first.
A value assigned to a shape needs every field the shape names, with the type it gives. A missing field or a field of another type is the error E0401. You can assign a new value to an existing field of an anonymous object. Adding a field it does not have throws a RuntimeError.
as Point checks the type of each field too. { x: 5, y: "six" } as Point throws a RuntimeError, and as ?Point gives null for it.
A /// comment above a field of a shape describes that field. The editor shows the text when you type the field's name in an object for that shape, or point at it.
is, new, clone, isset and empty
Eight small expressions that test a value, build one, copy one or stop the program.
$x is T is true when the value in $x is a T. Where the test is true, $x has the type T. $x is $cls tests against a class<T> variable. new C(...) builds an object.
clone $o makes a shallow copy. An object in a property is shared with the original. isset($x) is true when $x is there and is not null. empty($x) is true when $x is false by the truth table. Both work on a variable, a property or an array element.
Good to know: throw, print and exit are expressions too, so each can be the right side of ??. print writes one value and gives 1.
The examples below show a type test, an object and its copy, and settings that may be missing. The last two show all of these, and a string after is, which does not compile.
Checking what kind of value you have
<?nvs// Shows how `$x is T` checks what kind of value you have right now. Inside// the branch where the check is true, the value has that type. You can// read the value there without converting it first.
interface Reading{}
class Temperature implements Reading{ public function constructor(public float $celsius) {}}
class Humidity implements Reading{ public function constructor(public int $percent) {}}
class Report{ public static function line(mixed $reading): tainted string { if ($reading is Temperature) { // Here `$reading` is a `Temperature`, so its property is readable. return 'temperature ' . $reading->celsius; } if ($reading is int) { return 'count ' . $reading; } if ($reading is string) { return 'note ' . $reading; } return 'unknown reading'; }
// When the class is only known while the program runs, put it in a // `class<Reading>` variable. `$reading is $kind` then checks against it. public static function count(array<mixed> $readings, class<Reading> $kind): int { int $found = 0; foreach ($readings as mixed $reading) { if ($reading is $kind) { $found += 1; } } return $found; }}
// This prints: temperature 21.5echo Report::line(new Temperature(21.5)), "\n";
// This prints: count 3echo Report::line(3), "\n";
// This prints: note warmecho Report::line('warm'), "\n";
// This prints: unknown readingecho Report::line(true), "\n";
array<mixed> $readings = [new Temperature(21.5), new Humidity(40), new Temperature(19.0), 'warm'];
// `as class<Reading>` converts a class name in a string to a class reference.// It throws an error if the name is not a `Reading`.class<Reading> $kind = 'Temperature' as class<Reading>;echo Report::count($readings, $kind), ' ';
// `Humidity::class` is already a class reference, so you can pass it directly.// The two calls print: 2 1echo Report::count($readings, Humidity::class), "\n";temperature 21.5count 3note warmunknown reading2 1Building an object and copying it
<?nvs// Shows `new` and `clone`. `new` builds an object. `clone` makes a shallow// copy: numbers, text and arrays are copied, and an object held in a// property is shared between the original and the copy.
class Address{ public function constructor(public string $city) {}}
class Customer{ public array<string> $tags = [];
public function constructor( public string $name, public Address $address, ) {}}
Customer $original = new Customer('Ada', new Address('Berlin'));$original->tags[] = 'vip';
Customer $copy = clone $original;$copy->name = 'Grace';$copy->tags[] = 'trial';$copy->address->city = 'Hamburg';
// The name and the tag list were copied, so the original still has its own.// This prints: Ada vipecho $original->name, ' ', Core\Str::join($original->tags, ','), "\n";
// This prints: Grace vip,trialecho $copy->name, ' ', Core\Str::join($copy->tags, ','), "\n";
// The address is one object that both of them point at, so writing the// city through the copy changes what the original reads: Hamburg Hamburgecho $original->address->city, ' ', $copy->address->city, "\n";Ada vipGrace vip,trialHamburg HamburgReading settings that may be missing
<?nvs// Shows how a program reads settings that may be missing. `isset` is true// when a key is there and its value is not `null`. `empty` is true when the// value is false by the truth table, so `""` is empty too. `throw` is an// expression, so it can sit on the right of `??`.
class Config{ public static function start(array<?string> $settings): void { // A required setting. `??` gives the value when the key is there, // and throws when it is missing or `null`. string $host = $settings['host'] ?? throw new LogicError('host is required'); echo 'connecting to ', $host, "\n";
// An optional setting, with the default written after `??`. string $port = $settings['port'] ?? '5432'; echo 'port ', $port, "\n";
// `isset` tests a key without reading it, and reading it afterwards // is safe because the key is known to hold text. if (isset($settings['user'])) { echo 'user ', $settings['user'], "\n"; }
// `empty` is true for a key that is missing and for one that is `""`. if (empty($settings['label'])) { echo "no label\n"; } }}
// This prints four lines: connecting to db.internal, port 5432, user ada,// no label.Config::start(['host' => 'db.internal', 'user' => 'ada', 'label' => '']);
try { Config::start(['port' => '6000']);} catch (LogicError $e) { // This prints: not started: host is required echo 'not started: ', $e->message, "\n";}connecting to db.internalport 5432user adano labelnot started: host is requiredA copy a type test and isset on an array
<?nvs// Shows `clone`, `is`, `isset`, `empty`, `print` and `throw` in one short program.
class Inner{ public int $v = 1;}class Outer{ public Inner $in; public array<int> $list = []; public function constructor() { $this->in = new Inner(); $this->list[] = 1; }}
// The copy has its own array, so `$a->list` still has one element.// Both objects share the same `Inner`, so `$a->in->v` is 9 too.Outer $a = new Outer();Outer $b = clone $a;$b->list[] = 2;$b->in->v = 9;// This prints: 12 9 |echo Core\Arr::count($a->list), Core\Arr::count($b->list), ' ', $a->in->v, ' ', ($a == $b) as string, "|\n";
// Inside the `if`, `$m` is an `Inner`, so `$m->v` works. This prints: inner 1mixed $m = new Inner();if ($m is Inner) { echo 'inner ', $m->v, "\n";}
// `isset` is true only for the key `"j"`. A key set to `null` and a missing key are both false.?int $none = null;array<?int> $arr = ['k' => null, 'j' => 1];echo isset($none) as string, isset($arr['k']) as string, isset($arr['j']) as string, isset($arr['zz']) as string, '|';
// `print` writes `p` and a newline, and gives `1`. `echo` prints that `1` at the start of the next line.// This line and the one above print: 1|11|pecho empty($none) as string, empty($arr['zz']) as string, '|', print "p\n";
// `$name` is `null`, so `??` runs the `throw`. This prints: no name?string $name = null;try { string $s = $name ?? throw new LogicError('no name');} catch (LogicError $e) { echo $e->message, "\n";}12 9 |inner 11|11|p1no nameA class name in a string after is
<?nvs// Shows that the right side of `is` cannot be a `string`. Convert the name with `as class<T>` first.// proof: compile-error
class Box{}
class Check{ public static function test(mixed $v, string $name): bool { return $v is $name; }}error[E0496]: the right-hand side of `is` is a type or a class reference, and this is neither --> 05-a-class-name-in-a-string-after-is.nvs:12:22 |12 | return $v is $name; | ^^^^^ not a class name = help: a class name cannot come from a string. Write the class name, or convert the string first: `$name as class<Base>` gives a class reference that works here. The conversion checks that the class is a `Base`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
is works with every type a value can have: a class, an interface, int, ?int, null, a union such as int|string and an array type such as array<int>. When the declared type of the variable already gives the answer, the test is fixed while compiling. For an int variable, $n is int is always true and $n is string is always false.
The right side of is is a type. The only variable allowed there is a class<T> variable, as in $v is $cls. A string variable is the error E0496. Convert the name first with as class<T>.
new P without brackets is the same as new P(). The arguments work as in a method call, and named arguments work too. You can call a method on the new object directly: new P()->hi(). Inside a class, new self() builds the class itself, and new static() builds the class the method was called on.
These forms of new do not compile:
newwith an interface or anabstractclass is the errorE0785.new $c()with astringvariable is the errorE0496. The class must be written in the code.new P(...)is the errorE0740. A constructor is not a method, so use an anonymous function.
clone copies every property, and a readonly property too. The copy is a new object, so $p == $q is false after $q = clone $p. A class cannot change what clone does. A method named clone is an ordinary method, and clone does not call it. clone on an int or another type that is not an object is the error E0781. On a mixed value that is not an object, it throws a LogicError when it runs. On a ?Point value that is null, it compiles and throws a LogicError too.
throw takes a Throwable. throw "oops" is the error E0780. A throw can be the right side of ??, ?:, || and &&, or one result of a ternary.
print takes one value. print "a", "b" does not compile, and print [1] is the error E0707. print gives 1, so $n + print "x" prints x and gives $n + 1.
isset takes one or more operands, and is true only when every one has a value that is not null. Each operand is a variable, a property or an array element. A call or a literal is the error E0498. To test a call, write A::f() != null. A variable that was never declared is the error E0301, for empty too. An operand of a type without null, such as int, is always true.
A missing key at any level gives false: isset($a["q"]["y"]) is false when "q" is missing. A nullable object on the way needs ?->. isset($p->next->v) is the error E0459 when next is a ?P, and isset($p->next?->v) is false when next is null.
empty takes one operand, and that operand may be any expression, a call included. "0" and an empty array are empty, as the truth table says.
What a class cannot have
Novis classes do not have magic methods, anonymous classes or nested classes. Each one is a compile error, and the message names what to write instead.
No method name may start with _, so __get, __set, __call, __invoke, __clone, __destruct, __toString and the rest cannot be written. A property hook does the work of __get and __set. PropertyObserver sees every read and write of a class. Stringable gives a class its text form. A callable comes from fn or from a method reference such as Core\Str::length, so there are no callable objects. There is no destructor.
new class { … } does not exist. A class or an interface inside a class body does not compile. Every class is declared at the top level of a file, with a name. An enum and a type alias are the only types a class body can declare.
The examples below show a hook in place of __get, PropertyObserver in place of __set, a named class in place of an anonymous one, and two classes that do not compile.
A hook in place of a get method
<?nvs// Shows a property hook where PHP would write `__get`. The hook runs when the// property is read, so the class works the value out instead of storing it.
class Person{ public function constructor(public string $first, public string $last) {}
// `get => expr;` runs on every read of `$fullName`. public string $fullName { get => $this->first . ' ' . $this->last; }}
var $ada = new Person('Ada', 'Byron');
// This prints "Ada Byron".echo $ada->fullName, "\n";
// The value follows the properties it is worked out from. This prints// "Ada Lovelace".$ada->last = 'Lovelace';echo $ada->fullName, "\n";
// A hook belongs to one property, with a name and a type the compiler checks.// Your editor completes `$ada->fullName` as it does any other property.Ada ByronAda LovelacePropertyobserver in place of a set method
<?nvs// Shows `PropertyObserver` where PHP would write `__set`. One method sees every// write to every property the class declares. A program can keep a trail of what// changed without writing a setter for each property.
final class Profile implements PropertyObserver{ public string $displayName; public string $email; public string $changed = '';
public function constructor(string $displayName, string $email) { $this->displayName = $displayName; $this->email = $email; // The two writes above are already in the trail. This row comes from // the database, so the trail starts empty. $this->changed = ''; }
public function onPropertyGet(string $name, mixed $value): void { }
public function onPropertySet(string $name, mixed $value): void { // Writing a property in this method calls the method again. Test the // name first, or the program never stops. if ($name != 'changed') { $this->changed = $this->changed . $name . ' '; } }}
var $profile = new Profile('ada', 'ada@example.com');
$profile->displayName = 'Ada Lovelace';$profile->email = 'ada.lovelace@example.com';
// This prints "displayName email", the two properties that changed, in the// order they were written.echo $profile->changed, "\n";displayName emailA named class in place of an anonymous one
<?nvs// Shows a named class where PHP would write `new class { … }`. Novis has no// anonymous classes, so a one-off implementation of an interface gets a name.
interface Notifier{ public function notify(string $text): string;}
// This class is declared at the top level of the file, like every other class.class ConsoleNotifier implements Notifier{ public function notify(string $text): string { return 'console: ' . $text; }}
// A second one. A test uses this in place of the real notifier and then reads// what it collected.class RecordingNotifier implements Notifier{ public string $last = '';
public function notify(string $text): string { $this->last = $text; return 'recorded: ' . $text; }}
class Job{ public function constructor(private Notifier $notifier) {}
public function run(): string { return $this->notifier->notify('job finished'); }}
// This prints "console: job finished".echo (new Job(new ConsoleNotifier()))->run(), "\n";
// The same job, with a different notifier. This prints// "recorded: job finished" and then "job finished".var $recorder = new RecordingNotifier();echo (new Job($recorder))->run(), "\n";echo $recorder->last, "\n";console: job finishedrecorded: job finishedjob finishedA method name that starts with underscores
<?nvs// Shows that a method name cannot start with `__`. The error names the method// without the underscores.// proof: compile-error
class Legacy{ public function __get(string $name): mixed { return 1; }}error[E0111]: method names must be camelCase, e.g. `get` --> 04-a-method-name-that-starts-with-underscores.nvs:8:21 |8 | public function __get(string $name): mixed | ^^^^^ method name must be camelCase = suggestion: rename to `get`: `get`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.A class inside a class
<?nvs// Shows that a class cannot be declared inside another class. Move `Inner` to// the top level of the file.// proof: compile-error
class Outer { public class Inner { }}error[E0233]: a class or an interface is not declared in a class body --> 05-a-class-inside-a-class.nvs:7:5 |7 | public class Inner { | ^^^^^^^^^^^^^^^^^^^^... declared inside another type | (continues to line 8) = help: move it to file scope. Only an `enum` or a `type` alias can be declared in a class body
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A method whose name starts with __ is the error E0111. Its help names the method without the underscores, such as get for __get. __construct is the error E0114, and its help names constructor. A property whose name starts with _ is the error E0112.
new class { … } is the error E0244.
An object cannot be called like a function. $obj() is the error E0420. Call a method by its name, or use a method reference such as $obj->run(...).
A method called destructor is an ordinary method. It runs only when your code calls it.
Do and don’t
Section titled “Do and don’t”- Do use
clonewhen you need a separate copy to change. - Do use
?->and??for an object that can benull. - Don’t use
objectwhen you know the class. A class type lets the compiler check every call. - Don’t expect
==to compare properties. It checks if both sides are the same object. Only the values ofCore\Time, such asDate,DateTime,DurationandZone, are compared by their value.
