Skip to content

Type system

Timm Friebe edited this page Oct 22, 2017 · 5 revisions

XP Compiler supports a rich type system which allows specifying a variety of types ontop of what PHP supports.

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).

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)          // A function that takes an int and returns a string
(function(string, string): int)  // A function that takes two strings and returns an int (think strcmp)
(function(): void)               // A function that 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());
  }
}

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