Skip to content

Anonymous objects and shapes

{ x: 1, y: 2 } creates an anonymous object: an object without a class. Its type is a shape: { x: int, y: int }. You usually give a shape a name with type.

Anonymous objects

An anonymous object is an object with exactly the fields you write. You do not declare a class for it.

You write it as { x: 1, y: 2 } and read or change a field with $point->x. Its type is the shape { x: int, y: int }, and a type alias gives that shape a short name. A variable with at least those fields fits where the shape is needed. An object you write directly in that place may have only the fields of the shape. A field that may be missing is written label?: string, and ?? gives a value for the times it is not there.

Good to know: an object is a handle and not a value. Two variables can name one object, and == checks whether they do. It does not compare the fields, so two anonymous objects with equal values are never equal.

The examples below build a point and change it, then pass shapes into a method and back out, then return the result of a check as an object. Example 04 returns an object from an anonymous function, and example 05 does not compile.

A point and what holds it

<?nvs
// Builds a small object with the fields you name, then reads and changes
// them.
type Point = { x: int, y: int };
Point $start = { x: 1, y: 2 };
// A field is read and written with `->`.
echo $start->x, ',', $start->y, "\n";
$start->x = 10;
echo $start->x, "\n";
// `var` works out the type of an anonymous object for you, and a field can
// contain another anonymous object.
var $marker = { label: 'home', at: { x: 3, y: 4 } };
echo $marker->label, ' at ', $marker->at->x, ',', $marker->at->y, "\n";
// An object is a handle. Both variables name the same object here, so the
// change is visible through both of them.
Point $alias = $start;
$alias->y = 99;
echo $start->y, "\n";
// `==` checks whether two variables name one object. It does not compare the
// fields, so these two are different even with equal values.
Point $twin = { x: 10, y: 99 };
if ($start == $twin) {
echo "one object\n";
} else {
echo "two objects\n";
}
Output
1,2
10
home at 3,4
99
two objects

A shape as an input and a result

<?nvs
// Uses a named shape as the type of what a method takes and of what it
// returns. Any object with at least those fields fits.
type Money = { amount: int, currency: string };
class Prices
{
// The parameter takes any object that has these two fields.
public static function format(Money $price): string
{
return ($price->amount as string) . ' ' . $price->currency;
}
// A shape is also a return type, and the anonymous object is the result.
public static function double(Money $price): Money
{
return { amount: $price->amount * 2, currency: $price->currency };
}
}
Money $coffee = { amount: 350, currency: 'EUR' };
echo Prices::format($coffee), "\n";
echo Prices::format(Prices::double($coffee)), "\n";
// This object has a third field. It still fits, because it has the two
// fields the shape needs.
var $line = { amount: 120, currency: 'EUR', note: 'milk' };
echo Prices::format($line), "\n";
Output
350 EUR
700 EUR
120 EUR

The result of a check

<?nvs
// Returns the result of a check as an object and turns it into JSON, the
// way a small web handler does.
type Result = { ok: bool, message: string, code?: int };
class Signup
{
public static function check(string $email): Result
{
if (Core\Str::contains($email, '@')) {
return { ok: true, message: 'welcome' };
}
return { ok: false, message: 'that is not an email address', code: 422 };
}
}
array<string> $tried = ['ada@example.com', 'ada'];
foreach ($tried as string $position => string $email) {
Result $result = Signup::check($email);
// `code` is written `code?: int`, so it may be missing. `??` gives a
// value for the times it is not there.
echo $result->message, ' (', $result->code ?? 200, ")\n";
echo Core\Json::encode($result), "\n";
}
Output
welcome (200)
{"message":"welcome","ok":true}
that is not an email address (422)
{"code":422,"message":"that is not an email address","ok":false}

An object from an anonymous function

<?nvs
// Shows an anonymous function that returns an anonymous object.
type Point = { x: int, y: int };
// After `=>`, a `{` starts a block. The parentheses make it an object.
var $onXAxis = fn(int $x): Point => ({ x: $x, y: 0 });
Point $p = $onXAxis(5);
$p->y = 7;
echo $p->x + $p->y, "\n";
// Each call creates a new object, so `==` gives `false` here.
Point $q = $onXAxis(5);
echo ($p == $p) ? 'same' : 'different', ' ', ($p == $q) ? 'same' : 'different', "\n";
Output
12
same different

An object at the start of a statement

<?nvs
// Shows that a `{` at the start of a statement starts a block, so this
// program does not compile. Write `({ x: 1 });` instead.
// proof: compile-error
{ x: 1 };
Output
error[E0117]: an anonymous object here is ambiguous with a block
--> 05-an-object-at-the-start-of-a-statement.nvs:6:1
|
6 | { x: 1 };
| ^^^^^^^^ `{` already means a block in this position
= help: wrap it in parentheses: `({...})`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

A field name is a plain name with no quotes. {"x": 1} is the error E0101, and so is {...$p, y: 2}, because there is no spread for an object. A comma after the last field is allowed, and {} is an object with no fields. A field name written twice is the error E0494.

At the start of a statement and directly after the => of an anonymous function, { starts a block. An anonymous object there is the error E0117. Write it in parentheses: ({ x: 1 }); and fn(int $x): Point => ({ x: $x, y: 0 }).

The type of a field does not change. $p->x = "a"; on { x: 1 } is the error E0401. A field with another anonymous object in it, or a function, is allowed. Call that function as ($p->f)(1). $p->f(1) is the error E0477, because an anonymous object has no methods.

Reading a field the object does not have compiles, and throws a RuntimeError when it runs: ` $shape{x} has no field y . A field written b?: int is optional. Reading it when it is not there throws the same error, so read it with $r->b ?? 0. isset($r->b) is false` when it is not there.

When you write an anonymous object directly where a shape is needed, it may have only the fields of that shape. Another field is the error E0454, and the message suggests the field you probably meant. So { frezee: true } for { freeze?: bool } does not compile. A variable with more fields still fits the shape.

An object of a class fits a shape when it has public properties with those names and types. $v is Point checks every field and its type when the program runs. $v as Point runs the same check. If the check fails, it throws a RuntimeError.

clone $p gives a new object with the same fields, so $p == clone $p is false. Core\Json::encode($p) writes the fields sorted by name. echo $p compiles, and throws a RuntimeError when it runs, because an anonymous object has no string form.

  • Do use an anonymous object for a small group of values, like the result of a method.
  • Do name a shape with type when you use it in more than one place.
  • Don’t use an anonymous object when the data needs methods or checks. Write a class.
  • Don’t start a statement with { x: 1 }. It does not compile. Write ({ x: 1 }).