Table of Contents ¶
The Override attribute is the child class'counterpart to the parent class' abstract declaration. It is an optional annotation on a method, implemented with the <<Override>> user attribute. If the <<Override>> attribute is found on a method, and that method does not exist in the set of (non-abstract) methods inherited from parents, an error is thrown. In Hack partial mode, this has the effect of throwing when the parent is defined in PHP, since the typechecker cannot access the parent's method declarations. Consider the following:
// file1.php
<?hh
class CParent {
public function doStuff(): void {
return $this->implementation();
}
protected function implementation(): void {
echo 'parent implementation', "\n";
}
}
// file2.php<?phpclass Child extends CParent {
<<Override>> protected function implementation(): void {
echo 'child implementation', "\n";
}
}
If the parent class is (inadvertently) refactored to the following...
// file1.php
<?hhclass CParent {
public function doStuff(): void {
echo 'parent implementation', "\n";
}
}
... the <<Override>> annotation will result in a typechecker error, alerting the refactorer of CParent of the existence ofChild.
In Traits ¶
The <<Override>> annotation may also be added to trait methods, although with slightly different behavior than in standard classes. For trait methods annotated with <<Override>>, the check of whether the overridden method exists is deferred to the classes that use the trait.
<?hhtrait T1 {
<<Override>> // checked on use classes
function foo(): void {}
}
class C1 {
use T1; // error! foo is not an override}
class C2 {
function foo(): void {}
}
class C3 extends C2 {
use T1; // OK! C2's implementation is being overridden}
No comments:
Post a Comment