Skip to content

Type system

Timm Friebe edited this page Sep 9, 2019 · 5 revisions

XP Compiler supports a rich type system which allows specifying a variety of types ontop of what PHP supports. Types can be used on function and method parameters, their return value, and on properties. Types of local variables are inferred!

class Person {
  private int $id;
  private string $name;

  public function __construct(int $id, string $name) {
    $this->id= $id;
    $this->name= $name;
  }

  public function name(): string {
    return $this->name;
  }
}

Primitives

As in PHP, the primitive types int, float, bool and string are supported. They can be used in cast expressions such as:

$i= (int)"5"; // 5
$b= (bool)1;  // true

Arrays

The generic array is supported as well as array<int> (a zero-base list of integers) and array<string, int> (a map with string keys and integer values).

See also https://wiki.php.net/rfc/generic-arrays

Void

Functions and methods may declare they do not return anything by specifying their return type as void.

See also https://wiki.php.net/rfc/void_return_type

Functions

XP Compiler supports the generic callable as well as more specific function types:

(function(int): string)          // Takes an int and returns a string
(function(string, string): int)  // Takes two strings and returns an int (think strcmp)
(function(): void)               // Takes no arguments and does not return anything

See also https://docs.hhvm.com/hack/callables/introduction

Value types

Value types (classes and interfaces, e.g. \util\Date), are supported in the same manner than PHP; the instanceof operator allows testing. Inside a class, the keywords self, parent and static resolved to the surrounding class, its parent and the called class, respectively. The generic object type references any value type.

Type unions

To support the Robustness Principle ("be liberal in what you accept"), type unions were added:

class Users {
  public function user(int|string $id): User {
    return new User($this->conn->query('select * from user where id = %d', $id)->next());
  }
}

See also https://wiki.php.net/rfc/union_types and https://github.com/php/php-rfcs/pull/1

Iteration

The special type iterable specifies anything which can be used inside the foreach statement: arrays, maps, objects implementing the Iterator or IteratorAggregate interfaces and generators.

See also https://wiki.php.net/rfc/iterable

Nullable

Types can be declared nullable by prefixing them with a question mark, e.g. ?string or ?Date.

See also https://wiki.php.net/rfc/nullable_types

Clone this wiki locally