Converting with as
value as T converts a value to the type T. If the conversion is not possible, it throws an error.
as ?T gives null instead. To test the class of an object, use is.
The as operator
Changing a value into another type is written one way in Novis: as, followed by the type you want.
A conversion gives a value of that type, or it throws an error. It never rounds, never drops a fraction, and never uses a zero or an empty string instead. With as ?int, the result is null where the plain form would throw. Add ?? to use a default value instead.
as also checks an object against a shape, such as as Point. as class<T> turns a class name in a string into a class reference. Where a class<T> is expected, Foo::class needs no as.
Good to know: as converts only the value directly before it, so $a + $b as float converts $b alone.
The examples below read numbers out of text from outside the program, add up an order total, and skip a row that throws an error. Then they show which error each conversion throws and choose a class by its name. The last two do not compile.
Numbers out of text that came from outside
<?nvs// Shows how `as` converts text from a file, a form or a command line to a number.// The whole text must be a number.
array<string> $fields = ['12', '-4', '2.5', '19.90'];
int $units = $fields[0] as int;int $adjustment = $fields[1] as int;float $weight = $fields[2] as float;decimal $price = $fields[3] as decimal;
echo $units + $adjustment, "\n";echo $weight * 2, "\n";
// `as string` converts a number to text. A `decimal` keeps its two decimal places,// so this prints `19.90`.echo $price as string, "\n";echo ($units as string) . ' units', "\n";8519.9012 unitsWhen the text might not be a number
<?nvs// Input from users is often not a valid number. `as ?int` converts text to a whole number.// If that is not possible, the result is `null` and the program continues.// Only "30" converts here. The other three give `null`.
array<string> $answers = ['30', 'thirty', '30.5', ''];
// `??` replaces `null` with a default value. Here the default is 14 days.foreach ($answers as string $answer) { int $days = ($answer as ?int) ?? 14; echo 'a trial of ', $days, " days\n";}
// To tell the user which answers were wrong, compare the result with `null` yourself.foreach ($answers as string $answer) { if (($answer as ?int) == null) { echo "not a whole number: \"", $answer, "\"\n"; }}a trial of 30 daysa trial of 14 daysa trial of 14 daysa trial of 14 daysnot a whole number: "thirty"not a whole number: "30.5"not a whole number: ""An order total read from a form
<?nvs// An order is sent as rows of text: a quantity and a price.// `as uint` converts the quantity to a whole number that is not negative.// `as decimal` converts the price to an exact amount of money.// If a conversion fails, it throws an error. The program prints the row and skips it.
class Order{ public static function lineTotal(array<string> $row): decimal { uint $quantity = $row[0] as uint; decimal $price = $row[1] as decimal;
// `as decimal` converts only `$quantity`, the value directly before it. // The result is then multiplied by `$price`. return $quantity as decimal * $price; }}
array<array<string>> $rows = [ ['3', '19.90'], ['1', '4.05'], ['two', '9.99'],];
decimal $total = 0.00;
foreach ($rows as array<string> $row) { try { $total = $total + Order::lineTotal($row); } catch (RuntimeError $e) { echo 'left out a row whose quantity is not a number: ', $row[0], "\n"; }}
echo 'total ', $total as string, "\n";left out a row whose quantity is not a number: twototal 63.75Which error a conversion throws
<?nvs// Shows the order in which `as` runs, and which error a failed conversion throws.
// `as` converts only the value directly before it. `7 / 2 as int` is `7 / (2 as int)`.echo 7 / 2 as int, ' ', (7 / 2) as string, ' ', 1 + 2 as float, "\n";
string $digits = '42';int $n = $digits as int;echo $n + 1, ' ', '1e3' as float, ' ', 3.0 as int, "\n";
// `true` converts to "1". `false` and `null` convert to an empty string.echo true as string, '|', false as string, '|', null as string, "|\n";
float $f = 3.9;string $word = 'abc';int $neg = -1;
// A number that does not fit throws an `ArithmeticError`.try { echo $f as int, "\n";} catch (ArithmeticError $e) { echo $e->message, "\n";}try { echo $neg as uint, "\n";} catch (ArithmeticError $under) { echo $under->message, "\n";}
// Text that is not a number throws a `RuntimeError`.try { echo $word as int, "\n";} catch (RuntimeError $text) { echo $text->message, "\n";}
// `as ?int` gives `null` for each value that `as int` cannot convert.echo ($word as ?int) ?? -1, ' ', ($f as ?int) ?? -1, ' ', ($digits as ?int) ?? -1, "\n";3.5 3.5 343 1000 31|||cannot convert `float` 3.9 to `int`cannot convert `int` -1 to `uint`cannot convert a `string` of 3 bytes to `int`-1 -1 42A class name read while the program runs
<?nvs// Shows how `as class<T>` turns a class name into a class reference.
class Animal{ public function speak(): string { return '...'; }}
class Dog extends Animal{ public function speak(): string { return 'woof'; }}
// `Dog::class` is already a class reference, so it needs no `as`.// The compiler checks that `Dog` is an `Animal`.class<Animal> $folded = Dog::class;
// A name in a variable is checked while the program runs.string $name = 'Dog';class<Animal> $picked = $name as class<Animal>;Animal $pet = new $picked();echo $pet->speak(), ' ', ($pet is $folded) ? 'a Dog' : 'not', "\n";
// No class `Cat` exists, so the conversion throws a `RuntimeError`.string $missing = 'Cat';try { class<Animal> $bad = $missing as class<Animal>; echo (new $bad())->speak(), "\n";} catch (RuntimeError $e) { echo $e->message, "\n";}woof a Dogcannot convert a `string` to `class<Animal>`: it does not name a class that is a `Animal`A configured class with a default
<?nvs// Shows a class chosen by a setting, with a default class when the setting names no class.
interface Renders{ public static function extension(): string;}
class CsvReport implements Renders{ public static function extension(): string { return 'csv'; }}
// The default is `CsvReport::class`. It is checked while the program compiles.class<Renders> $fallback = CsvReport::class;
// No class `PdfReport` exists, so `as ?class<Renders>` gives `null`, and `??` uses the default.string $setting = 'PdfReport';class<Renders> $format = ($setting as ?class<Renders>) ?? $fallback;echo $format::extension(), "\n";csvA class name outside the hierarchy
<?nvs// Shows that a class name written in the code must name a class of the right type.// `Rock` does not extend `Animal`, so this program does not compile.// proof: compile-error
class Animal{}class Rock{}
class<Animal> $c = 'Rock' as class<Animal>;error[E0708]: `Rock` is not a `Animal`, so this can never be a `class<Animal>` --> 07-a-class-name-outside-the-hierarchy.nvs:11:20 |11 | class<Animal> $c = 'Rock' as class<Animal>; | ^^^^^^^^^^^^^^^^^^^^^^^ converted here = help: make `Rock` extend or implement `Animal`. Or write a class in `class<…>` that `Rock` already extends
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.A conversion that cannot fail
<?nvs// Shows that `as ?int` is not allowed on a value that is already an `int`.// The result can never be `null`, so write `as int`. This program does not compile.// proof: compile-error
int $i = 7;?int $a = $i as ?int;error[E0709]: `int as ?int` cannot fail, so it never answers `null` --> 08-a-conversion-that-cannot-fail.nvs:7:11 |7 | ?int $a = $i as ?int; | ^^^^^^^^^^ converted here = help: write `as int`. With `?`, every reader of the result would have to check for a `null` that the conversion never returns
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
as can be written more than once: $m as int as string converts to int and then to string.
A conversion that fails while the program runs throws one of two errors. A number that does not fit throws an ArithmeticError. These conversions throw it:
- a
floator adecimalwith a fraction toint - a negative number to
uint - an
intabove 2^53 tofloat
Every other failure throws a RuntimeError.
Text converts to a number only when the whole text is one number. " 42", "42 ", "", "0x1A", "1_000" and "12.0" all throw when converted to int. "+5" as int is 5. "1e3" as float is 1000, and ".5" and "5." are also valid float values. "inf" and "NAN" throw.
A float converts to decimal at the value it prints as. 0.1 as decimal is 0.1, not a long binary fraction. A string converts to decimal the same way: "1e3" as decimal is 1000.
true as string is "1". false as string and null as string are "". A bool does not convert to a number. $b as int is the error E0708, so write $b ? 1 : 0. Any value converts to bool by the truthiness table: "0", "", 0.0 and null are false.
string as bytes always works. bytes as string throws a RuntimeError when the bytes are not valid UTF-8.
An enum case converts to int or uint and gives its number. 5 as Rank throws a RuntimeError when no case of Rank has the number 5. An enum case does not convert to string.
A conversion between two types that has no rule is the error E0708, and the message names both types. An array, bytes and an enum case to string are three of them.
A mixed value converts by the type of the value it contains. Text from a mixed value is tainted, which means it may come from outside the program: $value as string gives a tainted string.
array<T> as array<U> checks each element. An element must already be a U, or be a number that widens to one, such as an int in an array<float>. The elements are not converted from text: ["1", "2"] as array<int> throws a RuntimeError.
?int as int throws a RuntimeError when the value is null. $object as Foo throws a RuntimeError when the object is not a Foo.
A value converts to a set of allowed values, such as "read"|"write", only when it equals one of them. Otherwise it throws a RuntimeError that lists the allowed values.
as ?T is not allowed where as T cannot fail. $i as ?int on an int is the error E0709. A class is not allowed either: $o as ?Foo is the error E0473, so use $o is Foo.
Where a class<T> is expected, Foo::class is already a class reference and needs no as. A class name in a string always needs as class<T>.
as class<T> checks a class name written in the code while the program compiles. That is Foo::class or a string literal such as 'Shop\Dog'. A name that is not a class is the error E0303, and a class that is not a T is E0708. This is the same with as ?class<T>. Every other string, including a class constant, is checked while the program runs. as class<T> then throws a RuntimeError, and as ?class<T> gives null.
A class name in a string is always the full name with its namespace. No namespace and no use applies to it. Inside namespace Shop, "Dog" as ?class<Animal> is null, and "Shop\Dog" finds the class.
A class<Dog> converts to class<Animal> without a check when Dog extends Animal. Back from class<Animal> to class<Dog>, the class it contains is checked, and the conversion throws a RuntimeError when that class is not a Dog.
Converting a mixed value to text
Section titled “Converting a mixed value to text”A mixed value may come from outside the program, for example from a request. So text you take
out of it is tainted (text that the program must not trust yet).
$value as stringgives atainted string, and$value as ?stringgives a?tainted string.$value as array<string>gives anarray<tainted string>.$value as int,as floatandas boolgive a plainint,floatorbool.$value as secret stringgives asecret tainted string.
Tainted input shows how to use tainted text safely.
Conversions without as
Some values are converted to a wider type without as. This happens when you assign a value, pass an argument, return a value or put an element in an array.
An int or a uint is converted to a float. A value is converted to a nullable type, to a union that contains its type, and to mixed. An object is converted to a parent class, to an interface its class implements, and to object. A single-value type such as "read" is converted to string.
Only the conversion to float changes the value. It is checked while the program runs. A number above 2^53 cannot be stored exactly in a float, so the program throws an ArithmeticError.
No other conversion happens without as. A string to a number, a number to a string, and an int to a uint each need as.
The examples below show a whole number used as a float, the wider types, a price list with both kinds of number, an anonymous object at a shape, and a program that assigns an int to a uint and does not compile.
A whole number where a fraction is wanted
<?nvs// Shows an `int` used where a `float` is needed, with no `as`. This works in an// assignment, an argument, a return value and a calculation.
class Cart{ public static function withTax(float $amount): float { return $amount * 1.2; }
public static function base(int $units): float { return $units; }}
int $units = 3;
float $stored = $units;echo $stored, "\n";
echo Cart::withTax($units), "\n";echo Cart::base($units), "\n";
float $rate = 1.5;echo $rate + $units, "\n";33.634.5Into a place that holds more
<?nvs// Shows a value assigned to a wider type with no `as`: a nullable type, a union// and `mixed`.
interface Sends{ public function send(): string;}
class Email implements Sends{ public function send(): string { return 'sent by e-mail'; }}
class Invoice extends Email{}
int $count = 3;
?int $optional = $count;int|string $either = $count;mixed $anything = $count;
echo $optional ?? 0, ' ', $either as string, ' ', $anything as string, "\n";
// An object is assigned to its parent class, to an interface its class// implements, and to `object`.Email $parent = new Invoice();Sends $contract = new Invoice();object $plain = new Invoice();
echo $parent->send(), "\n";echo $contract->send(), "\n";echo $plain is Email, "\n";3 3 3sent by e-mailsent by e-mail1A price list that mixes both
<?nvs// A price list for a small shop. Some prices are whole numbers and some are not.// A list with the type `array<float>` accepts both, and you do not write `as`.
// `var $prices = [4, 2.5, 3];` does not compile, because the values are `int` and `float`.// So the type is written here.array<float> $prices = [4, 2.5, 3];var $total = 0.0;
foreach ($prices as var $price) { echo $price, "\n"; $total = $total + $price;}
echo 'total ', $total, "\n";42.53total 9.5An anonymous object at a shape
<?nvs// Shows that the fields of an anonymous object are converted to the types of the shape.
type Point = { x: float, y: float };
// `x` and `y` are written as whole numbers. They are stored as `float` values.Point $p = { x: 2, y: 3 };echo $p->x / 4, ' ', $p->y / 4, "\n";
// A function that returns the shape converts its fields the same way.class Origin{ public static function point(): Point { return { x: 0, y: 1 }; }}
echo Origin::point()->y / 4, "\n";0.5 0.750.25An int into a uint
<?nvs// Shows that an `int` is not converted to a `uint` without `as`. Write `$i as uint`.// This program does not compile.// proof: compile-error
int $i = 3;uint $u = $i;error[E0401]: expected `uint`, found `int` --> 05-an-int-into-a-uint.nvs:7:11 |7 | uint $u = $i; | ^^ this is `int`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A number written in the code without a type takes the type of the place it goes to. It can be an int, a uint, a float or a decimal. decimal $d = 3; and array<float> $xs = [1, 2]; both compile.
An int or a uint above 9007199254740992 (2^53) throws an ArithmeticError when it is converted to a float. This is also true for a number that a float could store exactly, such as 9007199254740994.
A single-value type is converted to its base type. A "read"|"write" value is converted to string, and a true value to bool.
These assignments each need as or a test that narrows the type. Without it, each is the error E0401:
- an
intto auint, and auintto anint - a number to a
string, and astringto a number - a
floatto anint - a
mixedvalue to any other type - a
?intto anint. The help suggests$value ?? 0.
An anonymous object written at a shape type has its fields converted too. { x: 2 } at { x: float } stores 2.0. A shape value that already exists is not converted. A { x: int } value at { x: float } is the error E0401. Build a new value instead: { x: $old->x }.
Do and don’t
Section titled “Do and don’t”- Do use
as ?intwith??for input that may be wrong:($input as ?int) ?? 0. - Do use
as intwhen wrong input is an error. - Don’t write
(int)$value. It does not compile. Write$value as int. - Don’t round with
as int. UseCore\Math::roundfirst. - Don’t convert a
secretvalue toint. It does not compile. WriteCore\Secret::reveal($value, "reason") as int.
