Methods and inheritance
A method is a function inside a class. A class can extend another class and replace its methods.
A variable of type Animal can contain a Dog. Then a call runs the Dog version of the method.
Methods, self, static and parent
A method is a function that belongs to a class.
An instance method runs on one object, and $this is that object. A static method belongs to the class itself. It has no $this, and you call it as Class::method().
Three keywords call a method without writing the class name. self is the class the code is written in. static is the class the call was made on, which may be a subclass. parent is the class this one extends, so parent::format() calls the parent's version.
Good to know: a method with the return type static returns the object it was called on, or a new object of the same class. In a final class, static is that class, so the method may return any object of it, such as a stored one.
The examples below show the two kinds of method, self beside static in a subclass, and a subclass that calls its parent's version. Then come a chain of calls with an anonymous function that keeps $this, and a return type static that does not compile. The last one shows a final class that returns a stored object.
An instance method and a static method
<?nvs// Shows the two kinds of method. An instance method works on one object through// `$this`. A static method belongs to the class and needs no object.
class Temperature{ public function constructor(public readonly int $celsius) {}
// An instance method. `$this` is the object the method was called on. public function isFreezing(): bool { return $this->celsius <= 0; }
// A static method. It has no `$this`, so everything it needs is a parameter. public static function warmer(Temperature $a, Temperature $b): Temperature { if ($a->celsius > $b->celsius) { return $a; } return $b; }}
var $morning = new Temperature(-4);var $noon = new Temperature(11);
// Only the first of these two prints a line.if ($morning->isFreezing()) { echo "the morning is freezing\n";}if ($noon->isFreezing()) { echo "the noon is freezing\n";}
// This prints 11, which is the warmer of the two.echo 'warmer: ', Temperature::warmer($morning, $noon)->celsius, "\n";the morning is freezingwarmer: 11Self is where the code is static is who called it
<?nvs// Shows the difference between `self` and `static`. `self` is the class the code// is written in. `static` is the class the call was made on.
class Document{ public static function kind(): string { return 'document'; }
// `new static()` creates an object of the class that was called, so a // subclass gets one of its own kind. public static function create(): static { return new static(); }
public function describe(): string { return static::kind() . ' (this code is written in ' . self::kind() . ')'; }}
class Invoice extends Document{ public static function kind(): string { return 'invoice'; }}
echo Document::create()->describe(), "\n";echo Invoice::create()->describe(), "\n";document (this code is written in document)invoice (this code is written in document)A subclass calls the version its parent wrote
<?nvs// Shows `parent`. A subclass runs the constructor and the methods of the class// it extends, and adds its own work around them.
class Notification{ public function constructor(public string $subject) {}
public function format(): string { return '[note] ' . $this->subject; }}
class UrgentNotification extends Notification{ public function constructor(string $subject, public string $team) { // The parent's constructor assigns the properties the parent declares. parent::constructor($subject); }
public function format(): string { // `parent::format()` is the version above this one, not this one, so // this method does not call itself. return parent::format() . ' for ' . $this->team; }}
var $normal = new Notification('Backup finished');var $urgent = new UrgentNotification('Disk is full', 'operations');
echo $normal->format(), "\n";echo $urgent->format(), "\n";[note] Backup finished[note] Disk is full for operationsChaining and a function that keeps this
<?nvs// Shows a method that returns `$this`, so calls can be chained. It also shows// an anonymous function that keeps the object it was made on.
class Acc{ private int $n = 0;
public function bump(): self { $this->n = $this->n + 1; return $this; }
// The function reads `$this->n` when it is called, not when it is made. public function adder(): callable { return fn(int $k): int => $this->n + $k; }}
var $a = new Acc();var $f = $a->adder();$a->bump()->bump();
// `$n` is 2 now, so this prints `5`.echo $f(3) as int, "\n";5Static must return the called class
<?nvs// Shows that a method with the return type `static` cannot return `new self()`.// A call on a subclass would get the wrong class, so this does not compile.// proof: compile-error
class Builder{ public function copy(): static { return new self(); }}error[E0741]: a body declaring `static` returns a value that is not the called class --> 05-static-must-return-the-called-class.nvs:8:29 | 8 | public function copy(): static | ------ declared `static` here...10 | return new self(); | ^^^^^^^^^^ not the called class = help: `static` is the class the call named, which a subclass may be. Return `$this`, `new static(...)`, a variable inside `if ($x is static)`, or a variable declared with `static` in its type. Declare `self` if the declaring class is what is meant. In a `final` class `static` is that class, so any value of it may be returned
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Static in a final class
<?nvs// Shows that in a `final` class, `static` means that class, so a method may return a stored object.
final class Color{ // The first call to `named('red')` stores the color here. private static ?Color $red = null;
public function constructor(public string $name) {}
// `Color` is `final`, so it has no subclass, and `static` is always `Color`. // That is why this method may return the stored color. public static function named(string $name): static { if ($name != 'red') { return new static($name); } ?Color $stored = Color::$red; if ($stored != null) { return $stored; } Color $made = new Color('red'); Color::$red = $made; return $made; }}
// Both calls return the same stored object, so this prints `true`.echo Color::named('red') == Color::named('red') ? 'true' : 'false', "\n";echo Color::named('blue')->name, "\n";trueblueDetails
An anonymous function written inside a method keeps that method's $this. It may read the class's private properties and call its private methods.
A static method may also be called on an object: $a->s() calls A::s(). $a::s() is the error E0496, because the left side of :: must be a class name. An instance method called through the class, such as A::i(), is the error E0778. $this inside a static method is the error E0779.
self, static and parent work only inside a class. Outside one, self::class and static::class are the error E0702. parent:: in a class that extends no class is the error E0303. When the parent declares a constructor, the child's constructor must call parent::constructor(...) on every path. A path without the call is the error E0410.
A method that returns self returns the class the method is written in. On a subclass object, the result has the parent's type, so a method only the subclass has is the error E0405. Declare the return type static to keep the subclass. self also works as a parameter type.
A method that returns static may return $this, new static(...) or the result of a static:: call. It may also return a variable inside if ($x is static), or a variable declared with static in its type, such as array<static> $found. new self() or new A() there is the error E0741. new self() in a static method always creates the class the code is written in, even when the call was made on a subclass. static::method() reaches an abstract static method that a subclass writes.
$o is static checks whether $o is an object of the class the call names. A value written to a variable declared with static in its type must be such an object. Any other value is the error E1022.
static:: and is static inside an anonymous function are the error E0834. self::m() and parent::m() inside one call the class the function is written in.
Extending a class
A class can build on another class. extends names the parent, and the new class starts with everything the parent has.
The subclass keeps every property and method of the parent, and may write its own version of a method. parent:: reaches the version the parent wrote. When the parent has a constructor, the subclass constructor must call parent::constructor(...).
An abstract class is not finished. You cannot create an object of it, and a subclass must write each method it declares without a body. A final class cannot be extended, and a final method cannot be replaced. $x is T tests whether an object is a T.
Good to know: a class extends one parent only. To share behaviour between classes that are not related, use an interface.
The examples below show a subclass that adds to its parent, then an abstract class every subclass fills in, then a class the program picks while it runs. Examples 06, 09 and 10 show an abstract static method, is and a static call through a class value. The others show what does not compile.
A subclass adds to what its parent does
<?nvs// Shows `extends`. A subclass starts with everything its parent has, and// `parent::` runs the version the parent wrote.
class Invoice{ public function constructor(public string $customer, public int $cents) {}
public function line(): string { return $this->customer . ': ' . $this->cents . ' cents'; }}
class OverdueInvoice extends Invoice{ public function constructor(string $customer, int $cents, public int $days) { // The parent's constructor assigns the properties the parent declares. parent::constructor($customer, $cents); }
public function line(): string { // `parent::line()` is the version above this one, so this method adds // to that text instead of writing it again. return parent::line() . ', ' . $this->days . ' days late'; }}
// A subclass fits everywhere its parent fits, so both objects go in the// same array.array<Invoice> $book = [ new Invoice('Ada', 1200), new OverdueInvoice('Bo', 3400, 12),];
// Each object runs its own version of `line`.foreach ($book as Invoice $invoice) { echo $invoice->line(), "\n";}Ada: 1200 centsBo: 3400 cents, 12 days lateAn abstract class every subclass fills in
<?nvs// Shows `abstract` and `final`. An abstract class says which methods a// subclass has to write, and writes the work that is the same for all of them.
abstract class Exporter{ public function constructor(public string $title) {}
// This method has no body. Every subclass writes it. abstract public function row(string $value): string;
// This one has a body, and it calls the method that does not. public function render(array<string> $values): string { string $out = $this->title . "\n"; foreach ($values as string $value) { $out = $out . $this->row($value) . "\n"; } return $out; }}
// `final` says no class extends this one.final class CsvExporter extends Exporter{ public function row(string $value): string { return "\"" . $value . "\""; }}
final class ListExporter extends Exporter{ public function row(string $value): string { return '- ' . $value; }}
array<string> $names = ['Ada', 'Bo'];
// There is no object of `Exporter` itself. `array<Exporter>` still holds both// subclasses, because both are exporters.array<Exporter> $exporters = [new CsvExporter('names.csv'), new ListExporter('Names')];foreach ($exporters as Exporter $exporter) { echo $exporter->render($names);}names.csv"Ada""Bo"Names- Ada- BoA class the program picks while it runs
<?nvs// Shows `class<T>` and `is`. A job runner reads the name of a class from its// queue, makes an object of that class, and runs it.
class Task{ public function constructor(public string $subject) {}
public function run(): string { return 'nothing to do for ' . $this->subject; }}
class EmailTask extends Task{ public function run(): string { return 'email sent to ' . $this->subject; }}
class ReportTask extends Task{ public function run(): string { return 'report written for ' . $this->subject; }}
// In a real program these names come from a queue or a configuration file, so// they are text.array<string> $queue = ['EmailTask', 'ReportTask'];
foreach ($queue as string $name) { // `as class<Task>` converts the text to a class. It throws an error when // the text is not the name of a class that extends `Task`. class<Task> $cls = $name as class<Task>;
// `new $cls(...)` makes an object of that class. Task $task = new $cls('Ada'); echo $task->run(), "\n";}
// `is` tests what an object really is. `$first` is declared `Task`, and the// object in it is an `EmailTask`, so this prints the line below.Task $first = new EmailTask('Bo');if ($first is EmailTask) { echo "the first task is an email task\n";}email sent to Adareport written for Adathe first task is an email taskA subclass must call the parent constructor
<?nvs// Shows that a subclass constructor must call `parent::constructor(...)`// when the parent has a constructor. This one does not, so it does not compile.// proof: compile-error
class Base{ public function constructor(public int $a) {}}
class Child extends Base{ public function constructor(public int $b) {}}error[E0410]: `Child` extends another class, but a path through its constructor never calls `parent::constructor(...)` --> 04-a-subclass-must-call-the-parent-constructor.nvs:14:21 |14 | public function constructor(public int $b) | ^^^^^^^^^^^ missing call on some path
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.A subclass must write every abstract method
<?nvs// Shows that a class must write every `abstract` method of its parent.// `Blob` does not write `area`, so it does not compile.// proof: compile-error
abstract class Shape{ abstract public function area(): int;}
class Blob extends Shape{}error[E0449]: `Blob` does not declare `area`, which `Shape` requires --> 05-a-subclass-must-write-every-abstract-method.nvs:11:7 |11 | class Blob extends Shape | ^^^^ this class implements `Shape` = help: declare `area` here, or give `Shape` a default body for it
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.An abstract static method
<?nvs// Shows an `abstract static` method. Each subclass writes it, and a static// method of the parent calls it.
abstract class Page{ abstract public static function title(): string;
public static function heading(): string { // `self::title()` calls the class the method was called on. // For `Blog::heading()`, that is `Blog::title()`. return 'Title: ' . self::title(); }}
final class Blog extends Page{ public static function title(): string { return 'Blog'; }}
final class Shop extends Page{ public static function title(): string { return 'Shop'; }}
echo Blog::heading(), "\n";echo Shop::heading(), "\n";Title: BlogTitle: ShopAn abstract static method has no body to call
<?nvs// Shows that you cannot call an `abstract static` method on the abstract class.// `Page::title()` has no body, so this does not compile.// proof: compile-error
abstract class Page{ abstract public static function title(): string;}
echo Page::title(), "\n";error[E0835]: `Page::title()` is `abstract`, so it has no body to call --> 07-an-abstract-static-method-has-no-body-to-call.nvs:11:6 |11 | echo Page::title(), "\n"; | ^^^^^^^^^^^^^ called on `Page`, which does not give it a body = help: call it on a class that is not `abstract`, or, inside a method of `Page`, write `static::title()` to call the class the method was called on
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.No class extends a final class
<?nvs// Shows that no class can extend a `final` class. This does not compile.// To build on `Sealed`, put a `Sealed` object in a property and call its methods.// proof: compile-error
final class Sealed{}
class Widened extends Sealed{}error[E0783]: `Sealed` is `final`, so no class extends it --> 08-no-class-extends-a-final-class.nvs:9:23 |9 | class Widened extends Sealed | ^^^^^^ `Widened` names it as its superclass = help: remove `final` from the declaration of `Sealed` if other classes may extend it. Or store a `Sealed` in a property of `Widened`, and write `implements … by $property` to forward the calls to it
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Is checks the class its parents and its interfaces
<?nvs// Shows what `is` tests. It is true for the object's class, every parent class// and every interface they implement.
interface Marks{ public function mark(): string;}
class Base implements Marks{ public function mark(): string { return 'base'; }}
class Leaf extends Base{}
class Other{}
// This prints `1`, `1`, `1` and then an empty string, because `Leaf` is not `Other`.var $leaf = new Leaf();echo ($leaf is Leaf) as string, ($leaf is Base) as string, ($leaf is Marks) as string, '|', ($leaf is Other) as string, "|\n";
// Inside the `if`, `$o` has the type `Marks`, so `$o->mark()` compiles.object $o = new Other();if ($o is Marks) { echo $o->mark(), "\n";} else { echo "not marked\n";}111||not markedA static call through a class value
<?nvs// Shows the three ways to use a `class<T>` value: `new $cls(...)`,// `$cls::kind()` and `$r is $cls`.
class Report{ public function constructor(public string $title) {}
public static function kind(): string { return 'report'; }
public function render(): string { return static::kind() . ':' . $this->title; }}
class Invoice extends Report{ public static function kind(): string { return 'invoice'; }}
string $wanted = 'Invoice';class<Report> $cls = $wanted as class<Report>;Report $r = new $cls('March');
// `$cls::kind()` runs `Invoice::kind`, because `$cls` is `Invoice`.echo $r->render(), ' ', $cls::kind(), ' ', ($r is $cls) as string, "\n";invoice:March invoice 1New through a class value checks every subclass
<?nvs// Shows that `new $cls(...)` must work for every subclass of `Formatter`.// `Strict` needs two arguments, so this `new` with one does not compile.// proof: compile-error
class Formatter{ public function constructor(public string $prefix) {}}
class Strict extends Formatter{ public function constructor(string $prefix, public int $width) { parent::constructor($prefix); }}
class<Formatter> $cls = Formatter::class;Formatter $made = new $cls('p: ');echo $made->prefix, "\n";error[E0794]: `new` over `class<Formatter>` cannot check its arguments --> 11-new-through-a-class-value-checks-every-subclass.nvs:21:19 |21 | Formatter $made = new $cls('p: '); | ^^^^^^^^^^^^^^^ `Strict::constructor` is not compatible with `Formatter::constructor` = help: a class reference may hold any implementor, so every one of them has to accept the arguments written here — give `Strict` a constructor compatible with `Formatter`'s, or narrow this to `as class<Strict>` and instantiate that
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
extends names one class. extends A, B is a syntax error. A class that is not declared is the error E0303, and so is an interface after extends. A class that extends itself, directly or through another class, is the error E0305.
When the parent has a constructor, every path through the subclass constructor must call parent::constructor(...). A call inside one if branch only is the error E0410. Code may run before the call, and a second call runs the parent's constructor again. When the parent has no constructor, the subclass does not call one, and parent::constructor() is the error E0309. A subclass with no constructor uses the parent's constructor.
A subclass can use the parent's public and protected methods and properties. A private one is the error E0471 in the subclass. parent:: in a class with no parent is E0303. parent::f() runs the nearest version above the class. When the parent does not declare f, it calls the grandparent's method. A default parameter value comes from the declared type of the variable. Say A::f(int $x = 1) is replaced by B::f(int $x = 2). A call on an A variable uses 1, even when it contains a B.
A class that does not write every abstract method of its parent is the error E0449. An abstract class that extends another one does not need to write them. new on an abstract class or on an interface is the error E0785. new static() inside an abstract class compiles, because it makes an object of the subclass the call was made on. A method without a body in a class that is not abstract is the error E0786, and so is an abstract method there. A method cannot be both abstract and final: that is the error E0106.
An abstract static method has no body, so a call to it must reach a subclass. self::title() and static::title() in a static method call the class the method was called on. Page::title() on the abstract class is the error E0835. self::title() inside an anonymous function is E0835 too, because it calls the class the function is written in.
A class that extends a final class is the error E0783. A method that replaces a final method is the error E0784, also in a grandchild class. Other methods of the same class can be replaced as usual.
$x is T is true for the object's own class, every parent class, and every interface they implement. It is false for any other class, and false when $x is null. Inside the if, the variable has the type T. The right side of is is a class name or a class<T> value. A string there is the error E0496.
A class<T> value works in three places: new $cls(...), $cls::f(...) and $x is $cls. A string in any of them is the error E0496. $obj->$name with a string is the error E0235. A static call through a class<T> value runs the subclass's method, and static:: in it is that subclass. new $cls(...) checks the arguments against the constructor of T. When a subclass of T has a constructor that cannot take those arguments, the new is the error E0794. Convert to the subclass, as in as class<Strict>, or give the subclass a constructor that fits.
Where a class<T> is expected, write a class as Strict::class, with no as. A class name in a string needs as class<T>. A class name written in the code that is not a subclass of T is the error E0708, with or without as.
A child method can take a narrower parameter type with covariant.
Do and don’t
Section titled “Do and don’t”- Do use
staticwhen a child class should be able to change what a method returns. - Do call
parent::constructor(...)first in a child constructor. - Don’t extend a class that extends another class many times. An interface is often simpler.
- Don’t look for traits. They do not exist. Use an interface with default methods instead.
