Variables and var
Every variable has a type. You declare a variable once, with its type or with var. After that,
you assign new values without the type.
Declaring a variable
Every variable in a program has a type, and the type never changes.
The short way to declare a local variable is var. var $count = 3; gives $count the type of its first value, int. In a foreach loop over an array, var gives the value the type of the array's values, and the key is a string. Over a Core\ObjectMap, the key gets the map's key type.
You can also write the type yourself, as in float $weight = 1;. Write it when the value comes later, when the variable needs a wider type, or when the type helps the reader. Parameters, return values, properties and the variable in catch always have a written type.
A value of another type does not compile, and neither does reading a variable before it has a value.
Good to know: a variable belongs to the whole function, not only to its block. So you can read a loop counter after the loop.
The examples below show var, a written type, a loop counter read after its loop, and an order whose values all have a type. The last two do not compile.
Var or a written type
<?nvs// Shows the two ways to declare a variable: with `var`, or with a written type.
// `var` gives the variable the type of its first value.// `$count` is an `int` and `$label` is a `string`. The types never change.var $count = 3;var $label = 'boxes';$count = $count + 1;
// A written type is needed when the variable gets its value later.string $unit;$unit = 'kg';
// A written type can also be wider than the first value.// With `var $weight = 1;` the type is `int`, so the next line would not compile.float $weight = 1;$weight = $weight * 2.5;
// This prints `4 boxes, 2.5 kg each`.echo $count, ' ', $label, ', ', $weight, ' ', $unit, " each\n";4 boxes, 2.5 kg eachA loop counter outlives the loop
<?nvs// A variable belongs to the whole function, not only to the block where it is declared.// So you can read the loop counter `$i` after the loop ends.
var $entries = ['12', 'nine', '30'];var $total = 0;
// `var $i = 0` makes the counter an `int`.for (var $i = 0; $i < Core\Arr::count($entries); $i = $i + 1) { try { $total = $total + ($entries[$i] as int); } catch (Throwable $e) { // The variable in `catch` always has a written type. echo 'skipped ', $entries[$i], ': ', $e->message, "\n"; }}
// This prints `read 3 entries, total 42`.echo 'read ', $i, ' entries, total ', $total, "\n";skipped nine: cannot convert a `string` of 4 bytes to `int`read 3 entries, total 42Price up an order
<?nvs// Prices an order the way a small shop does. Every value has a type: the constant,// the property, the method's parameter and return value, and each variable.
class Order{ public const int TAX_PERCENT = 20;
public string $customer;
public function constructor(string $customer) { $this->customer = $customer; }
public function net(array<decimal> $lines): decimal { decimal $sum = 0; // In a `foreach`, `var $amount` gets the type of the array's values, `decimal`. // `var $item` gets the key's type, `string`. foreach ($lines as var $item => var $amount) { echo $item, ': ', $amount, "\n"; $sum = $sum + $amount; } return $sum; }}
var $order = new Order('Blog Press');
// The type is written here because `var` would make these prices `float`.// A `decimal` keeps exact cents, so `120.00` prints with both zeros.array<decimal> $lines = ['print run' => 120.00, 'delivery' => 15.50];
// `var $net` gets the type `decimal` from the value that `net` returns.var $net = $order->net($lines);decimal $gross = $net + $net * Order::TAX_PERCENT / 100;
echo $order->customer, ' owes ', $gross, ' (', $net, " plus tax)\n";print run: 120.00delivery: 15.50Blog Press owes 162.60 (135.50 plus tax)A variable keeps its type
<?nvs// Shows that a variable keeps the type of its declaration. `$count` is an `int`,// so the string on the last line does not compile.// proof: compile-error
int $count = 1;$count = 'two';error[E0401]: expected `int`, found `string` --> 04-a-variable-keeps-its-type.nvs:7:10 |7 | $count = 'two'; | ^^^^^ this is `string`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Var needs one element type
<?nvs// Shows that `var` needs an array whose elements have one type. This array has// an `int` and a `string`, so this program does not compile.// proof: compile-error
var $xs = [1, 'two', 3];error[E0414]: `var` cannot infer an array whose elements have different types --> 05-var-needs-one-element-type.nvs:6:11 |6 | var $xs = [1, 'two', 3]; | ^^^^^^^^^^^^^ the elements are `int` and `string` = help: write the type: `array<int|string> $xs = [1, 'two', 3];`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A variable is declared once. Every later $count = … is an assignment and has no type. A value of another type does not compile: $count = "two"; after var $count = 1; is the error E0401. The message points to the line that gave $count its type.
int $i = null; and uint $u = -1; are the error E0401 too. The only conversion without as is widening, such as an int value in a float variable.
Assigning to a variable that was never declared is the error E0301. Reading a variable before every path has given it a value is also the error E0301.
var needs a value whose type it can see. var $xs = []; does not compile, because an empty array has no element type. var $xs = [1, "a"]; does not compile either, because the elements have two types. Both are the error E0414, and the message shows the type to write, such as array<int|string> $xs = [1, "a"];.
The variable of a catch clause is a declaration too. Two catch clauses in one function may use the same name when they catch the same type.
Do and don’t
Section titled “Do and don’t”- Do write the type when it helps the reader, such as for a function result.
- Do use
varwhen the value already shows the type. - Don’t use one variable for values of different types. Declare a second variable.
- Don’t use
varfor an empty array. Writearray<string> $names = [];.
