echo, unset and exit
echo writes values to the output. unset removes entries from an array. exit ends the program.
echo, print, unset, exit and yield
echo, print, unset, exit and yield are five short statements: they write output, remove an array entry, end the program, and produce values one at a time.
echo a, b, c; writes several values in order with nothing between them. print $value; writes one value, and its result is 1. Both turn a value into text the same way . does: true writes 1, and false and null write nothing.
unset($a["k"]); removes that entry from the array $a, and nothing else. Every variable and every property in Novis always has a value, so unset($x) and unset($o->p) do not compile. Assign null instead, where the type allows it.
exit; ends the program with status 0. exit(3); ends it with status 3, and exit("bye") writes the text and then ends with status 0.
yield $value; goes inside a method that returns Iterator<T>. It sends one value to the loop that reads it. A yield is a statement, so $x = yield 1; does not compile.
The examples below show echo and print, then unset on array entries, then a check that reads rows with yield and stops with exit. The last one is an unset that does not compile.
Writing values with echo and print
<?nvs// Shows how `echo` and `print` write values. `echo` takes several values at// once and writes them in order with nothing between them.
string $name = 'Ada';int $orders = 3;
// This prints: Ada has 3 ordersecho $name, ' has ', $orders, ' orders', "\n";
// `print` writes one value.print "report finished\n";
// A value becomes text the same way `.` does. `true` writes `1`, and `false`// and `null` write nothing, so this line prints 1|||echo true, '|', false, '|', null, '|', "\n";Ada has 3 ordersreport finished1|||Removing the entries you are done with
<?nvs// Shows how `unset` removes entries from an array. Only an array entry can be// removed. A variable always has a value in Novis, so `unset($x)` does not// compile.
array<int> $stock = ['apple' => 4, 'pear' => 0, 'plum' => 7, 'fig' => 0];
// One call removes several entries. This prints {"apple":4,"plum":7}unset($stock['pear'], $stock['fig']);echo Core\Json::encode($stock), "\n";
array<int> $counts = [10, 20, 30];
// Removing an entry in the middle leaves a gap. The entries after it keep the// keys they had, so this prints {"0":10,"2":30}unset($counts[1]);echo Core\Json::encode($counts), "\n";
// Removing a key that is not in the array does nothing, and is not an error.// There are still 2 entries.unset($counts[99]);echo Core\Arr::count($counts), "\n";{"apple":4,"plum":7}{"0":10,"2":30}2Ending a check at the first bad row
<?nvs// Shows a small check program. It reads rows one at a time with `yield`,// writes a line for each good row, and ends with `exit` at the first bad one.
class Rows{ // Each `yield` sends one row to the loop below. public static function all(): Iterator<string> { yield 'ada,42'; yield 'grace,17'; yield 'broken row'; yield 'alan,9'; }}
foreach (Rows::all() as string $row) { if (Core\Str::contains($row, ',') == false) { // `exit` with a text writes it and ends the program with status 0. // The rows after this one are never read. exit('stopped at a bad row: ' . $row . "\n"); } echo 'ok: ', $row, "\n";}
echo "every row is good\n";ok: ada,42ok: grace,17stopped at a bad row: broken rowUnset needs an array entry
<?nvs// Shows that `unset` only removes array entries. A variable always has a// value, so `unset($x)` does not compile.// proof: compile-error
int $x = 1;unset($x);error[E0234]: `unset()` takes an array element of a named holder --> 04-unset-needs-an-array-entry.nvs:7:7 |7 | unset($x); | ^^ this is not an array element = help: `unset()` removes an array element and nothing else. A variable always has a value. If its type is nullable, assign `null` to it
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
One unset can remove several entries: unset($a["k"], $a["j"]);. Removing a key that is not in the array does nothing. The entries after a removed one keep their keys.
unset($x) on a variable does not compile: it is the error E0234. unset($o->p) on a property does not compile either: that is the error E0413.
exit("bye") writes the text to standard output. exit is also an expression, so int $n = $value ?? exit(4); ends the program with status 4 when $value is null.
yield outside a generator does not compile: it is the error E0445. A method that contains yield must return Iterator<T>, or it is the error E0446.
yield from does not exist: it is the error E0448. Write a foreach loop that yields each value instead.
Iterators and generators explains yield.
Statements Novis does not have
Novis reads PHP syntax, but not all of it. A few PHP statement forms do not parse. For most of them, the compiler error names what to write instead.
goto and its labels are gone: use a loop, an early return, or a flag. declare(strict_types=1) is not needed, because every Novis file is strict already. The alternative syntax if (…): … endif; is not accepted: write braces. Instead of global $x;, pass the value as a parameter, or keep it in a private static property. That property is also what replaces a static variable inside a function. Write [int $a, int $b] = … instead of list($a, $b) = …, and require instead of include or require_once. A class, interface, enum, type, namespace, use or autoload statement goes at the top of a file, never inside a body.
The examples below show what to write instead of goto, instead of global and a static variable, and instead of list() and the alternative syntax. The last two are a goto and an if (…): … endif; that do not compile.
What to write instead of goto
<?nvs// `goto` and its labels do not parse. Shows the three ways to leave a piece of// work early instead: an early `return`, a `break`, and a flag.
class Orders{ // Returns the first total above the limit, or 0 when there is none. public static function firstOver(array<int> $totals, int $limit): int { foreach ($totals as int $total) { // An early `return` leaves the method at once. if ($total > $limit) { return $total; } } return 0; }}
array<int> $totals = [400, 1200, 250, 3000];
// This prints 1200.echo Orders::firstOver($totals, 1000), "\n";
// `break` leaves a loop. This one stops at the first total below 300.int $small = 0;foreach ($totals as int $total) { if ($total < 300) { $small = $total; break; }}
// This prints 250.echo $small, "\n";
// A flag carries the decision to the statements after the loop.bool $found = $small > 0;if ($found) { echo "one small order\n";}1200250one small orderWhat to write instead of global and a static variable
<?nvs// `global $x;` and a `static` variable inside a function do not parse. Shows// what to write instead: a parameter, and a `private static` property.
class Retry{ // The count belongs to the class, so it is still there on the next call. private static int $attempts = 0;
// The limit arrives as a parameter. Nothing is read from outside. public static function attempt(int $limit): bool { self::$attempts = self::$attempts + 1; return self::$attempts <= $limit; }
public static function attempts(): int { return self::$attempts; }}
int $round = 0;while ($round < 3) { // The first two calls are allowed, the third is not. if (Retry::attempt(2)) { echo 'attempt ', Retry::attempts(), ": allowed\n"; } else { echo 'attempt ', Retry::attempts(), ": too many\n"; } $round = $round + 1;}attempt 1: allowedattempt 2: allowedattempt 3: too manyWhat to write instead of list and the alternative syntax
<?nvs// `list($a, $b) = …` and the alternative syntax `if (…): … endif;` do not// parse. Shows the two replacements in a program that reads contact lines.
array<string> $lines = ['Ada Lovelace|ada@example.com', 'Grace Hopper|'];
foreach ($lines as string $line) { // Brackets replace `list()`. Each name is written with its type, as // everywhere else. [string $name, string $mail] = Core\Str::split($line, '|');
// Braces replace `if (…): … endif;`. if ($mail == '') { echo $name, " has no address\n"; } else { echo $name, ' <', $mail, ">\n"; }}Ada Lovelace <ada@example.com>Grace Hopper has no addressGoto does not compile
<?nvs// Shows that `goto` is not allowed. The compiler error names the three ways// to write it instead. This program does not compile.// proof: compile-error
int $n = 0;while ($n < 3) { $n++; if ($n == 2) { goto done; }}error[E0203]: `goto` is not supported --> 04-goto-does-not-compile.nvs:10:9 |10 | goto done; | ^^^^^^^^^^ makes the control-flow graph unstructured = help: restructure with a loop, an early `return`, or a boolean flag
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.The alternative syntax does not compile
<?nvs// Shows that the alternative syntax `if (…): … endif;` is not allowed. Write// braces instead. This program does not compile.// proof: compile-error
int $n = 2;if ($n == 2): echo "two";endif;error[E0102]: expected an expression --> 05-the-alternative-syntax-does-not-compile.nvs:7:13 |7 | if ($n == 2): | ^ not found here
error[E0101]: expected `;` --> 05-the-alternative-syntax-does-not-compile.nvs:7:13 |7 | if ($n == 2): | ^ not found here
error[E0319]: `endif` is not a constant that exists --> 05-the-alternative-syntax-does-not-compile.nvs:9:1 |9 | endif; | ^^^^^ no global constant has this name = help: every constant belongs to a class, so write `Class::NAME`. A built-in constant is on its `Core` class, such as `Core\Math::PI`
error: aborting due to 3 errorsTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
Each form has its own error code:
gotois the errorE0203.global $x;is the errorE0204.static $n = 0;inside a method is the errorE0209.list($a, $b) = …is the errorE0230.includeandrequire_onceare the errorE0221.- A
class,interface,enum,type,namespaceorusestatement inside a body is the errorE0233.
A label, declare(…) and the alternative syntax give a general syntax error. That error does not name what to write instead. The alternative syntax is the colon form of if, while, for, foreach and switch, with endif, endwhile, endfor, endforeach and endswitch.
In [int $a, int $b] = …, each variable needs its type. [$a, $b] = … does not compile, even when $a and $b are already declared.
| Statement | Use instead |
|---|---|
goto and labels |
a loop, an early return, or a bool variable |
declare(...) |
nothing. Every file is already strict |
if (...): with endif;, endwhile; and the other end forms |
braces |
global $x; |
a parameter, or a static property |
static $n = 0; inside a method |
a private static property |
list($a, $b) = ... |
[int $a, int $b] = ... |
include, require_once |
require |
class, interface, enum, namespace or use inside a body |
write it at the top level of the file |
Use this when you stop a script with an error
Section titled “Use this when you stop a script with an error”exit(1) ends a command line program with the status 1. When the cause is an error that code
around it can handle, throw an error instead.
Do and don’t
Section titled “Do and don’t”- Do put
"\n"at the end of anechowhen you want a new line. - Do assign
nullto clear a nullable variable. - Don’t use
unseton a variable. It does not compile. - Don’t call
exitinside a library method. Throw an error, so the caller can handle it.
