Nullable types
?T is a T or null. A type without ? can never be null. $a ?? $b gives $a when it is
not null, and $b when it is. To use the value itself, test it with == null or != null
first. Type tests with is shows how a test changes the type.
$user->name on a ?User does not compile until you test $user. $user?->name needs no test.
When $user is null, the result is null.
Nullable, union and single-value types
A nullable type ?T is the type T or null. A variable can be null only when its type allows it. A union A|B is either of the two types. Test which one a value is with is before you use it as one of them.
A single-value type is one value written as a type, such as "asc" or 3. A union of them is a list of allowed values. A setting that may only be one of three words has a type that names those three words. Any other word is not accepted. An enum case is a type in the same way, so a function can accept two cases of an enum and not the third.
The examples below show a setting that may be missing, a sort order limited to three words, and a handler that converts an untrusted request into the values it accepts. The last three show each kind of type at once, and two compile errors.
A setting that may not be there
<?nvs// A setting may be missing. `?uint` is a whole number or `null`.// `as ?uint` converts text to a whole number. If the text is not a number,// the result is `null`, and `??` gives a default value.
array<string> $settings = ['page' => '3', 'limit' => 'many'];
?uint $page = $settings['page'] as ?uint;?uint $limit = $settings['limit'] as ?uint;
echo 'page ', $page ?? 1, "\n";echo 'limit ', $limit ?? 20, "\n";
// A variable can be `null` only when its type allows it, as `?string` does.// So the reader can see on this line that `$note` may be empty.?string $note = null;echo 'note ', $note ?? '(none)', "\n";page 3limit 20note (none)A sort order that may only be one of three words
<?nvs// The type of `$order` is a set of three words. Only those words can be passed to `sortBy`,// so `sortBy` does not need to check its argument. For any other word, `as` throws// an error before the method is called.
class Report{ public static function sortBy("newest"|"oldest"|"name" $order): string { return 'sorting by ' . $order; }}
array<string> $asked = ['newest', 'name', 'sideways'];foreach ($asked as string $one) { try { echo Report::sortBy($one as "newest"|"oldest"|"name"), "\n"; } catch (Throwable $e) { echo 'not a sort order: ', $one, "\n"; }}sorting by newestsorting by namenot a sort order: sidewaysA handler that accepts only what it will act on
<?nvs// A handler converts each field of a request to the exact type it needs, once, at the top.// The account is an `int` or a `string`, and the action is a case of the enum `Gate::Action`.// `grant` accepts only the cases `Read` and `Write`. Converting `Delete`// to that type throws an error, so `grant` is never called with it.
class Gate{ enum Action { Read, Write, Delete }
public static function grant(Action::Read|Action::Write $action, int|string $account): string { array<string> $verbs = ['read', 'write', 'delete']; return 'account ' . ($account as string) . ' may ' . $verbs[$action as int]; }}
array<array<string>> $requests = [ ['account' => '1042', 'action' => '0'], ['account' => 'ada', 'action' => '1'], ['account' => 'ada', 'action' => '2'],];
foreach ($requests as array<string> $request) { try { string $raw = $request['account']; int|string $account = ($raw as ?int) ?? $raw; Gate::Action $asked = ($request['action'] as int) as Gate::Action; echo Gate::grant($asked as Gate::Action::Read|Gate::Action::Write, $account), "\n"; } catch (Throwable $e) { echo "refused: this gate grants nothing else\n"; }}account 1042 may readaccount ada may writerefused: this gate grants nothing elseEach kind of type
<?nvs// Shows a nullable type, a union, two single-value types and an enum case type.
enum Mode: int{ Read = 1, Write = 2,}
?int $maybe = null;int|string $id = 'abc';"read"|"write" $mode = 'read';1|2|3 $level = 2;Mode::Read|Mode::Write $m = Mode::Write;
// `$m as int` gives the number of the case, here `2`. `1 as Mode` gives the case `Mode::Read`.echo $maybe ?? -1, ' ', $id, ' ', $mode, $level, ' ', $m as int, ' ', (1 as Mode) == Mode::Read ? 'read' : 'other', "\n";
// No case has the number `9`, so `as Mode` throws an error.try { Mode $none = 9 as Mode;} catch (RuntimeError $e) { echo $e->message, "\n";}
// `as ?Mode` gives `null` for the same number.echo (9 as ?Mode) == null ? 'null' : 'case', "\n";-1 abc read2 2 read`9` is not one of `Mode::Read`, `Mode::Write`nullA word outside the list
<?nvs// Shows that a variable of the type `"read"|"write"` only accepts those two words.// `"delete"` is not one of them, so this program does not compile.// proof: compile-error
"read"|"write" $mode = 'read';$mode = 'delete';error[E0401]: expected `"read"|"write"`, found `string` --> 05-a-word-outside-the-list.nvs:7:9 |7 | $mode = 'delete'; | ^^^^^^^^ this is `string`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Nothing is an iterable
<?nvs// Shows that no value can be assigned to an `iterable` variable, not even an array.// This program does not compile.// proof: compile-error
array<int> $xs = [1, 2];iterable $i = $xs;error[E0401]: expected `iterable`, found `array<int>` --> 06-nothing-is-an-iterable.nvs:7:15 |7 | iterable $i = $xs; | ^^^ this is `array<int>`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
null is a type of its own, and null $n = null; compiles. int $i = null; is the error E0401. A ?int value is not used in arithmetic before it is tested. $maybe + 1 is the error E0716. Test it with != null first, or give a default with ??.
A union may mix any types, such as object|int. Inside if ($id is int), $id is an int.
A value written in the code is checked against a single-value type when the program compiles. $mode = "delete"; for a "read"|"write" variable is the error E0401. A value converted with as is checked when the program runs. If it is not in the list, as throws a RuntimeError. A single-value type can be assigned to its wider type: a 1|2|3 value to an int.
An enum is a list of named whole numbers. enum Mode { Read, Write } numbers its cases from 0. enum Mode: int { Read = 1 } gives each case its number. $m as int gives the number of a case. 1 as Mode gives the case with that number. If no case has it, as throws a RuntimeError, and as ?Mode gives null. Mode::Read as string is the error E0708.
iterable and an intersection A&B can be written for a parameter or a return type. No value can be assigned to either of them. iterable $i = $xs; is the error E0401.
Do and don’t
Section titled “Do and don’t”- Do use
?Tfor a value that can be missing, such as an optional setting. - Do give a default with
??when one makes sense. - Don’t use
?Twhen the value is always there. Every reader then has to handlenull.
