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";hello, Adahello, strangersend mailno mailfull pricediscountA for adano badgeOne 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";tap to payinsert the cardpaid by cardcounted outcash, counted outa note that says keep the changesomething elseA 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";running as admin; failures go to ops@example.comreading only; nobody is toldTwo 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";3.503-1A 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";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 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
Four tests narrow a variable:
$x == nulland$x != nullon a?T. Each narrows on the branch where the value is notnull.!swaps the two branches, soif (!($x == null))narrows its block.$x is Con a?C, a union,objectormixed. Only the branch where the test is true narrows. Afterif ($pet is Cat) { return …; },$petis stillDog|Cat, and$pet->speak()does not compile (E0477).$x == "read"or$x == Mode::Readon 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 eachcaseofswitch (true)narrows its own code when its label is one of the tests above.defaultnarrows 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.
Testing for int or string
Section titled “Testing for int or string”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 and don’t
Section titled “Do and don’t”- Do test with
isbefore you call a method that only one class has. - Do use
match (true)for three or more tests. - Don’t convert with
as Catwhen the value may be another class.asthrows an error then.
