Declaring a class
A class describes a kind of object. It has properties, which contain the object’s data, and
methods, which are functions that work on that data. Inside a method, $this is the object the
method was called on. An enum can be declared inside a class. See Enums.
Declaring a class
A class is a type you write yourself. It holds some data and the functions that work on that data. You create one with new.
Every member of a class writes public, protected or private. A public member is reachable from anywhere. A protected member is reachable from the class and from the classes that extend it. A private member is reachable only from the class that declares it. There is no default, so a member written without one of those three words does not compile.
The constructor is a method named constructor. It runs once, when new creates the object. It must give a value to every property that has no default. A class where every property already has a default needs no constructor.
Good to know: a visibility keyword in front of a constructor parameter declares a property of that name and fills it with the argument.
The examples below show a class with data and methods, a constructor that declares its properties, and a class that keeps its data private. The last two show a property with no visibility, which does not compile, and a class with no constructor.
A class with data and methods
<?nvs// Shows how to declare a class, create an object with `new`, and use it.// Every member writes `public`, `protected` or `private`.
class User{ public string $name; public string $email; private string $role = 'member';
public function constructor(string $name, string $email) { $this->name = $name; $this->email = $email; }
public function label(): string { return $this->name . ' <' . $this->email . '>'; }
public function roleName(): string { return $this->role; }}
var $user = new User('Ada Lovelace', 'ada@example.com');
// A `public` property is read and written from anywhere with `->`.$user->email = 'ada@example.org';
// This prints `Ada Lovelace <ada@example.org>`.echo $user->label(), "\n";
// `$role` is `private`. Only `User`'s own methods read it, so this class gives// you a method for it. This prints `member`.echo $user->roleName(), "\n";Ada Lovelace <ada@example.org>memberA constructor that declares the properties
<?nvs// Shows constructor promotion. A visibility keyword on a constructor parameter// declares a property of that name and type, and assigns the argument to it.
class Product{ // These three lines declare three properties and fill them. There is no // second place where `$name`, `$priceCents` and `$currency` are written. public function constructor( public string $name, public int $priceCents, private string $currency = 'EUR', ) {}
public function price(): string { return $this->priceCents . ' ' . $this->currency; }}
var $book = new Product('The Art of Computer Programming', 8990);
// A default on the parameter is a default for the argument. `$currency` is// `EUR` here, because the third argument was left out.var $mug = new Product('Coffee mug', 1250, 'CHF');
// This prints `The Art of Computer Programming: 8990 EUR`.echo $book->name, ': ', $book->price(), "\n";
// This prints `Coffee mug: 1250 CHF`.echo $mug->name, ': ', $mug->price(), "\n";The Art of Computer Programming: 8990 EURCoffee mug: 1250 CHFA class that collects and sums its own data
<?nvs// Shows the shape most classes in a program have: private data, and public// methods that are the only way to reach it.
class Cart{ private array<int> $prices = [];
public function constructor(private string $currency) {}
public function add(int $priceCents): void { $this->prices[] = $priceCents; }
public function total(): int { int $sum = 0; foreach ($this->prices as int $price) { $sum = $sum + $price; } return $sum; }
public function summary(): string { return Core\Arr::count($this->prices) . ' items, ' . $this->total() . ' ' . $this->currency; }}
var $cart = new Cart('EUR');$cart->add(1250);$cart->add(399);$cart->add(8000);
// Nothing outside `Cart` can change the prices, so `total` is always the sum of// what `add` was given. This prints `3 items, 9649 EUR`.echo $cart->summary(), "\n";3 items, 9649 EURA member with no visibility
<?nvs// Shows that every property needs `public`, `protected` or `private`.// `$balance` has none, so this program does not compile.// proof: compile-error
class Account{ int $balance = 0;}error[E0122]: a property must declare `public`, `protected` or `private` --> 04-a-member-with-no-visibility.nvs:8:9 |8 | int $balance = 0; | ^^^^^^^^ no visibility written here = suggestion: write `public`: `public `
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.A class with no constructor
<?nvs// Shows a class with no constructor. Every property has a default, so `new`// takes no arguments.
class Counter{ public int $n = 0;}
var $c = new Counter();$c->n = $c->n + 1;
// This prints `1`.echo $c->n, "\n";1Details
A property, a method or a constant written without public, protected or private does not compile (E0122). A method named __construct does not compile either (E0114). The error tells you to name it constructor. A class name is PascalCase, so class point is the error E0110.
Reading a property or calling a method where its visibility does not allow it is the error E0471. That includes a private property read in a class that extends the declaring class. A private constructor works the same way. new A() outside A is E0471, and a static method of A may still call new A().
A class is declared at the top level of a file. A class or an interface inside a class body is the error E0233. Only an enum or a type alias may be declared there. A class inside a method or an if block is E0233 too.
A wrong number of arguments is the error E0402. An unknown method or property is E0405, for a read and for a write. A class with no constructor takes no arguments, so new Counter(1) is E0402. A class that extends another and declares no constructor uses its parent's: with class B extends A {}, new B(4) calls A's constructor.
A visibility keyword is allowed only on a parameter of constructor. On any other method it is the error E0722. A promoted parameter may also be readonly: public readonly int $x.
new A without parentheses is the same as new A(). A constructor may declare the return type void, and it may have no return type at all.
Do and don’t
Section titled “Do and don’t”- Do write the visibility on every property, method and constant. Start with
private. Change it toprotectedorpubliconly when needed. - Do use constructor parameters as properties when the constructor only copies its arguments.
- Don’t name the constructor
__construct. It does not compile. Name itconstructor. - Don’t try to add a property that the class does not declare. It does not compile.
