Skip to content

Annotations

Timm Friebe edited this page Mar 6, 2021 · 6 revisions

XP Compiler supports annotations with PHP 8 attribute syntax. Annotations can be placed on types, methods, fields as well as method parameters.

Basic syntax

The most simple form of an annotation is simply its name as a literal, e.g. Test. Annotations may have a value, which is enclosed in braces, e.g. Author('Timm Friebe'). Annotations are surrounded by #[ and ], and separated by commas.

use unittest\actions\RuntimeVersion;
use unittest\{Test, Expect, Action};
use lang\IllegalArgumentException;

#[Action(new RuntimeVersion('>=7.0'))]
class URLTest {

  #[Test]
  public function can_create() {
    new URL('http://url');
  }

  #[Test, Expect(IllegalArgumentException::class]
  public function cannot_create_with_malformed_scheme() {
    new URL('http:--');
  }
}

Annotation values

The value inside an annotation can be any of the following:

  • A primitive value
  • An array
  • A map
  • A class constant, including the ::class special constant
  • A static member variable
  • An instance creation expression, as seen above
  • A function

Parameter annotations

Parameter annotations are written inside the parameter list, and before the parameter they belong to:

class Synchronize extends Command {

  public function __construct(#[Inject(name: 'api.url')] string $url) {
     // …
  }
}

Further reading

XP RFCs:

PHP RFC:

Clone this wiki locally