Skip to content

Interfaces

An interface is a list of methods. A class that implements the interface must have every method in the list. Then you can use the class wherever the interface type is needed.

Interfaces

An interface is a list of methods a class promises to provide. A class writes implements and then writes those methods.

A class may implement many interfaces, and an interface may extend another one. A variable typed as an interface accepts any class that implements it. A class that leaves out a required method does not compile.

An interface may also have a method with a body. Every class that implements the interface gets that method and may replace it. An interface may also have constants and static methods.

Two interfaces may both give a class a method with the same name. Then the class must declare that method itself, or it does not compile.

Good to know: Novis has no trait. To share methods, write them in an interface. To pass the work to another object, write implements Greets by $voice. Every method of Greets then calls the same method on the object in $voice.

The examples below show a class that implements an interface, an interface with its own method, and a class that passes its work to another object. Examples 04 and 05 show more of an interface, and the others do not compile.

A class promises what an interface lists

<?nvs
// Shows `implements`. An interface lists the methods a class must write, and
// a variable declared at the interface holds any class that implements it.
interface Priced
{
public function cents(): int;
}
interface Named
{
public function name(): string;
}
// A class implements as many interfaces as it needs, separated by a comma.
class Book implements Priced, Named
{
public function constructor(private string $title, private int $cents)
{}
public function cents(): int
{
return $this->cents;
}
public function name(): string
{
return $this->title;
}
}
class Shipping implements Priced
{
public function cents(): int
{
return 499;
}
}
// Both classes fit here, because both are `Priced`.
array<Priced> $order = [new Book('Novis', 2500), new Shipping()];
int $total = 0;
foreach ($order as Priced $item) {
$total = $total + $item->cents();
}
echo 'total ', $total, " cents\n";
Output
total 2999 cents

An interface brings a method of its own

<?nvs
// Shows a method with a body inside an interface. Every class that implements
// the interface gets that method, and may write its own version instead.
interface Greets
{
public const int MAX_LEN = 20;
// No body: every class writes this one.
public function name(): string;
// A body: every class gets this one for free. It calls `name`, which the
// class provides.
public function greet(): string
{
return 'Hello, ' . $this->name() . '!';
}
}
class Person implements Greets
{
public function constructor(private string $who)
{}
public function name(): string
{
return $this->who;
}
}
class Shop implements Greets
{
public function name(): string
{
return 'the shop';
}
// This class writes its own version. `Greets::greet()` is still the
// interface's version, so this method adds to it.
public function greet(): string
{
return Greets::greet() . ' How can we help?';
}
}
echo (new Person('Ada'))->greet(), "\n";
echo (new Shop())->greet(), "\n";
// A constant on an interface is read through the interface or through any
// class that implements it. Both print 20.
echo Greets::MAX_LEN, ' ', Person::MAX_LEN, "\n";
Output
Hello, Ada!
Hello, the shop! How can we help?
20 20

One class passes the work to another

<?nvs
// Shows `implements I by $property`. A class that holds an object which already
// does the work passes every method of the interface on to it.
interface SendsMail
{
public function send(string $to, string $subject): string;
public function name(): string;
}
// The class that really sends the mail.
class SmtpMailer implements SendsMail
{
public function send(string $to, string $subject): string
{
return "sent \"" . $subject . "\" to " . $to;
}
public function name(): string
{
return 'smtp';
}
}
// This class is a `SendsMail` too. `by $inner` writes the forwarding methods,
// so it does not repeat them.
class LoggingMailer implements SendsMail by $inner
{
public function constructor(private SendsMail $inner)
{}
// A method the class writes itself is used instead of the forward.
public function name(): string
{
return 'logging(' . $this->inner->name() . ')';
}
}
SendsMail $mailer = new LoggingMailer(new SmtpMailer());
// `send` is forwarded to the object in `$inner`.
echo $mailer->send('ada@example.com', 'Welcome'), "\n";
// `name` is the method this class wrote.
echo $mailer->name(), "\n";
Output
sent "Welcome" to ada@example.com
logging(smtp)

A private helper and a static method

<?nvs
// Shows the parts an interface can have: a required method, a default method,
// a private helper, a constant and a static method.
interface Greets
{
public const int MAX_LEN = 20;
public function name(): string;
public function greet(): string
{
return $this->prefix() . $this->name() . '!';
}
// Only the methods of `Greets` can call this one.
private function prefix(): string
{
return 'Hello, ';
}
public static function kind(): string
{
return 'greeter';
}
}
interface Counts
{
public function count(): int;
}
class Person implements Greets, Counts
{
public function constructor(private string $who)
{}
public function name(): string
{
return $this->who;
}
public function count(): int
{
return 1;
}
}
// `parent::greet()` runs the default method that `Person` got from `Greets`.
class Loud extends Person
{
public function greet(): string
{
return Core\Str::upper(parent::greet());
}
}
echo (new Person('ada'))->greet(), ' ', Greets::MAX_LEN, ' ', Person::kind(), "\n";
echo (new Loud('bob'))->greet(), "\n";
Output
Hello, ada! 20 greeter
HELLO, BOB!

An interface extends another

<?nvs
// Shows an interface that extends another one. A class that implements
// `Titled` must write the methods of both interfaces.
interface Named
{
public function name(): string;
}
interface Titled extends Named
{
public function title(): string;
}
class Doc implements Titled
{
public function name(): string
{
return 'doc';
}
public function title(): string
{
return 'Doc';
}
}
// A `Doc` is a `Named` too. This prints `doc 1`.
Named $n = new Doc();
echo $n->name(), ' ', ($n is Titled) as string, "\n";
Output
doc 1

A class must write every required method

<?nvs
// Shows that a class must write every method its interface requires.
// `Empty` does not write `count`, so it does not compile.
// proof: compile-error
interface Counts
{
public function count(): int;
}
class Empty implements Counts
{
}
Output
error[E0449]: `Empty` does not declare `count`, which `Counts` requires
--> 06-a-class-must-write-every-required-method.nvs:11:7
|
11 | class Empty implements Counts
| ^^^^^ this class implements `Counts`
= help: declare `count` here, or give `Counts` a default body for it
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

The forward needs a property that is never null

<?nvs
// Shows that `by $voice` needs a property that is never `null`.
// `$voice` is `?Greets`, so this does not compile.
// proof: compile-error
interface Greets
{
public function greet(): string;
}
class Maybe implements Greets by $voice
{
private ?Greets $voice;
public function constructor(?Greets $voice)
{
$this->voice = $voice;
}
}
Output
error[E0720]: `$voice` is `null|Greets`, which cannot satisfy `Greets`
--> 07-the-forward-needs-a-property-that-is-never-null.nvs:11:34
|
11 | class Maybe implements Greets by $voice
| ^^^^^^ a delegate is dispatched on at every forwarded call, so it may not be nullable
= help: declare `$voice` as `Greets`, or as a class that implements it. The type cannot be nullable
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

There is no trait

<?nvs
// Shows that `trait` does not exist, so this does not compile.
// To share a method, write it with a body in an interface.
// proof: compile-error
trait Greets {
public function hi(): string {
return "hi";
}
}
Output
error[E0227]: traits do not exist
--> 08-there-is-no-trait.nvs:6:1
|
6 | trait Greets {
| ^^^^^^^^^^^^^^... not supported
| (continues to line 10)
= help: for shared methods, write a default or private method in an interface. For shared state, write `implements Interface by $property;`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

An interface has no properties. public string $path; in an interface is the error E0254. A constant in an interface needs a type, as in any class: public const MAX = 3; is the error E0246. A class may declare the constant again with its own value. A default method reads the value of the class with static::MAX, and the interface's value when the class has none.

A private method with a body is a helper. Only the interface's own methods can call it. A call from anywhere else is the error E0435. A class that replaces a default method can still call the interface's version with Greets::greet(). A subclass calls its parent's version with parent::. A default method cannot read a property, because the interface has none: $this->name there is the error E0313. It calls a method instead.

A static method with a body is called as Greets::kind() or Person::kind(), and a class may replace it. A static method without a body must be written by every class, like any other method.

A class that does not write a required method is the error E0449. The message names the method and the interface. A name after implements that is a class is the error E0303. A name after an interface's extends that is a class is E0303 too. An interface may extend several interfaces, separated by commas. Two interfaces that extend each other are the error E0305. When a class extends a parent class and also gets a default method of the same name from an interface, the parent's method is used.

When two interfaces give a class default methods with the same name, the class must declare that method itself. Otherwise it is the error E0859. Its body can call A::h() and B::h().

implements Greets by $voice needs a property named $voice. A missing property is the error E0720. The property's type must be the interface, or a class that implements it. A ?Greets property, an int property and a class that only has the same methods are all the error E0720. The forward covers the methods without a body. A default method of the interface still runs its own body, and calls the class's methods. The forward reads the property on every call, so assigning a new object to it changes where later calls go. A lateinit property that is not set yet throws LogicError on the first forwarded call. A static method, a method with a ... parameter and a method with an inout parameter cannot be forwarded. Each is the error E0721, and the class must write that method itself. One implements list may mix interfaces with by and without it.

trait, use T; in a class body and insteadof are all the error E0227.

A final class cannot be extended. Store an object of that class in a property, and forward to it with implements Greets by $voice.

To add a method to an interface of another package, write an extend block. In a file that uses the block, every class that implements the interface has the method.

  • Do use an interface type for a parameter when any class with those methods will do.
  • Do put shared code in a default method.
  • Don’t declare properties in an interface. They do not compile.
  • Don’t write trait. Traits do not exist. Use default methods for shared code and by for shared data.