Expressions And Operators: Is

Operator is determines if the value designated by its left-hand operand has the type specified by the right-hand one. The operator returns a bool result. The operator refines the type of its left-hand operand when used in an if statement, invariant, or ternary expression.

Operator is should be used instead of instanceof or calls to library functions like is_bool, is_int, and so on.

For example:

1 is int        // true
'foo' is int    // false
1 is num        // true
1.5 is num      // true
'foo' is num    // false

For enums, the operator validates that the value is in the given enum.

enum MyEnum: int {
  FOO = 1;
1 is MyEnum       // true
42 is MyEnum      // false
'foo' is MyEnum   // false

For generic types, we must use the _ (wildcard) placeholder for the type parameters.

interface MyInterface<T> {}
$x is MyInterface<_>;

For tuples and shapes, operator is validates the size and recursively validates every field in the value.

$x is (int, ?string, bool)

For type aliases and type constants, the operator tests the value against the underlying runtime type.

The nonnull type is handled specially; if the left-hand operand of is nonnull is known to be of type ?T, it is refined to T, instead of simply to nonnull.