Skip to content

Type tests with is

$value is Cat is true when $value is a Cat object. Inside the branch where the test is true, the variable has the type Cat.

How a test changes the type

A test that proves what a value is lets you use it as that thing, in the code the test guards.

The shortest form is one expression: $user != null ? $user->name : "guest". The right side of && runs only when the left side is true, so $user != null && $user->active works too. An if block or a match (true) arm does the same for more code. You can test for null, test the kind of object with is, or compare with a fixed word.

Good to know: a test works only for a variable or a readonly property, and only until you write to the variable. Copy any other property, such as $job->mode, to a variable first.

The examples below use a value that might be null, check the kind of an object, and act on a job's settings. The last two check two values in one test, and show a method call that does not compile.

A value that might be missing

<?nvs
// Shows how to use a value that might be `null` once you have checked it.
class Account
{
// In `$nickname != null ? A : B`, the value is a `string` inside `A`.
// So `A` can use it like any other string.
public static function greeting(?string $nickname): string
{
return $nickname != null ? 'hello, ' . Core\Str::upperFirst($nickname) : 'hello, stranger';
}
// The right side of `&&` runs only when the left side is true.
// So on the right side, `$email` is a `string`.
public static function canReceiveMail(?string $email): bool
{
return $email != null && Core\Str::contains($email, '@');
}
// The right side of `||` runs only when the left side is false.
// So on the right side, `$coupon` is a `string`.
public static function paysFullPrice(?string $coupon): bool
{
return $coupon == null || Core\Str::startsWith($coupon, 'EXPIRED-');
}
// An `if` block does the same for several lines of code.
// After the `return`, the rest of the method uses `$nickname` as a `string`.
public static function badge(?string $nickname): string
{
if ($nickname == null) {
return 'no badge';
}
string $initial = Core\Str::upper(Core\Str::slice($nickname, 0, 1));
return $initial . ' for ' . $nickname;
}
}
echo Account::greeting('ada'), "\n";
echo Account::greeting(null), "\n";
echo Account::canReceiveMail('ada@example.com') ? 'send mail' : 'no mail', "\n";
echo Account::canReceiveMail(null) ? 'send mail' : 'no mail', "\n";
echo Account::paysFullPrice(null) ? 'full price' : 'discount', "\n";
echo Account::paysFullPrice('SPRING10') ? 'full price' : 'discount', "\n";
echo Account::badge('ada'), "\n";
echo Account::badge(null), "\n";
Output
hello, Ada
hello, stranger
send mail
no mail
full price
discount
A for ada
no badge

One of several kinds of thing

<?nvs
// Shows how to check which kind of object a value is, and then use it as that kind.
class Card
{
public function constructor(public bool $contactless)
{}
public function pay(): string
{
return 'paid by card';
}
}
class Cash
{
public function count(): string
{
return 'counted out';
}
}
class Till
{
// On the right side of `&&`, `$payment` is a `Card`.
// So the right side can read the `contactless` property.
public static function canTap(Card|Cash $payment): bool
{
return $payment is Card && $payment->contactless;
}
// Inside the `if` block, `$payment` is a `Card`. After it, the type is still `Card|Cash`.
// `as Cash` converts it to `Cash`, and throws an error if it is not `Cash`.
public static function take(Card|Cash $payment): string
{
if ($payment is Card) {
return $payment->pay();
}
return ($payment as Cash)->count();
}
// Each arm of `match (true)` uses the value as the kind that arm checked.
public static function describe(mixed $thing): tainted string
{
return match (true) {
$thing is Card => 'a card, ' . $thing->pay(),
$thing is Cash => 'cash, ' . $thing->count(),
$thing is string => 'a note that says ' . $thing,
default => 'something else',
};
}
}
echo Till::canTap(new Card(true)) ? 'tap to pay' : 'insert the card', "\n";
echo Till::canTap(new Cash()) ? 'tap to pay' : 'insert the card', "\n";
echo Till::take(new Card(false)), "\n";
echo Till::take(new Cash()), "\n";
echo Till::describe(new Cash()), "\n";
echo Till::describe('keep the change'), "\n";
echo Till::describe(7), "\n";
Output
tap to pay
insert the card
paid by card
counted out
cash, counted out
a note that says keep the change
something else

A jobs settings read once and acted on

<?nvs
// A job's settings are a mode, which is one of three words, and a mailbox that may be `null`.
// Checking a property such as `$job->mode` does not change its type.
// Checking a local variable does. So `plan` copies each property to a variable first.
class Job
{
public ?string $failureMailbox = null;
public "read"|"write"|"admin" $mode = 'read';
}
class Runner
{
public static function plan(Job $job): string
{
?string $mailbox = $job->failureMailbox;
"read"|"write"|"admin" $mode = $job->mode;
string $notify = $mailbox != null ? 'failures go to ' . $mailbox : 'nobody is told';
if ($mode == 'admin') {
// Inside this `if`, `$mode` can only be "admin". So it can be
// assigned to a variable of type "admin".
"admin" $elevated = $mode;
return 'running as ' . $elevated . '; ' . $notify;
}
if ($mode == 'write') {
return 'writing; ' . $notify;
}
return 'reading only; ' . $notify;
}
}
Job $nightly = new Job();
$nightly->mode = 'admin';
$nightly->failureMailbox = 'ops@example.com';
Job $report = new Job();
echo Runner::plan($nightly), "\n";
echo Runner::plan($report), "\n";
Output
running as admin; failures go to ops@example.com
reading only; nobody is told

Two values checked in one test

<?nvs
// Shows that one test with `&&` or `||` can check two values that might be `null`.
class Sum
{
// The block runs only when both tests are true. So both values are a `float` there.
public static function both(?float $a, ?float $b): float
{
if ($a != null && $b != null) {
return $a + $b;
}
return 0.0;
}
// The code after the `return` runs only when both values are not `null`.
public static function guarded(?float $a, ?float $b): float
{
if ($a == null || $b == null) {
return -1.0;
}
return $a + $b;
}
}
echo Sum::both(1.5, 2.0), "\n";
echo Sum::both(null, 2.0), "\n";
echo Sum::guarded(1.0, 2.0), "\n";
echo Sum::guarded(1.0, null), "\n";
Output
3.5
0
3
-1

A method call on a value that might be null

<?nvs
// Shows that `->` on a value that might be `null` does not compile.
// `$d` has the type `?Dog` and no test checks it, so this program does not compile.
// proof: compile-error
class Dog
{
public function speak(): string
{
return 'woof';
}
}
?Dog $d = new Dog();
echo $d->speak(), "\n";
Output
error[E0459]: `null|Dog` may be `null`, so `->` cannot reach a member of it
--> 05-a-method-call-on-a-value-that-might-be-null.nvs:15:6
|
15 | echo $d->speak(), "\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 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

Four tests narrow a variable:

  • $x == null and $x != null on a ?T. Each narrows on the branch where the value is not null. ! swaps the two branches, so if (!($x == null)) narrows its block.
  • $x is C on a ?C, a union, object or mixed. Only the branch where the test is true narrows. After if ($pet is Cat) { return …; }, $pet is still Dog|Cat, and $pet->speak() does not compile (E0477).
  • $x == "read" or $x == Mode::Read on a set of allowed values or a union of enum cases. The right side must be a value written in the code or an enum case. A comparison with a variable narrows nothing. The branch where the test is false keeps the full type. It is not narrowed to the values that are left.
  • Each arm of match (true) and each case of switch (true) narrows its own code when its label is one of the tests above. default narrows nothing.

A ternary's two arms and the right side of && and || are narrowed like the branches of an if. What a test proves ends with the expression. After $d != null ? $d->speak() : "none", $d is a ?Dog again.

The block of if ($a != null && $b != null) sees both variables narrowed. After if ($a == null || $b == null) { return …; }, the code below also sees both narrowed. The else of an && and the block of an || narrow nothing, because only one of the two tests is known there.

A write to the variable inside the branch ends the narrowing. An assignment narrows nothing. After $box = new Box(); on a ?Box variable, $box->count is still E0459. A property is narrowed when it is readonly, and so is every property before it in the path, such as $app->config->parent. Any other property, such as $d->friend, is never narrowed, because a call can change it between the test and the read. Copy it to a local variable first. A -> on a ?C that is not narrowed does not compile (E0459). $d?->speak() needs no test: when $d is null, the result is null.

is also tests for a type such as int or string. $value is int is true only when $value is an int. The string "7" is not an int. To accept "7" as a number, convert it: ($value as ?int) != null.

A mixed value may come from outside the program. So after $value is string, $value has the type tainted string (text that the program must not trust yet). See Tainted input.

  • Do test with is before you call a method that only one class has.
  • Do use match (true) for three or more tests.
  • Don’t convert with as Cat when the value may be another class. as throws an error then.