language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Markdown
hhvm/hphp/hack/manual/hack/02-source-code-fundamentals/31-variables.md
A variable is a named area of data storage that has a type and a value. Distinct variables may have the same name provided they are in different [scopes](scope.md). A [constant](constants.md) is a variable that, once initialized, its value cannot be changed. Based on the context in which it is declared, a variable ...
Markdown
hhvm/hphp/hack/manual/hack/02-source-code-fundamentals/34-script-inclusion.md
When creating large applications or building component libraries, it is useful to be able to break up the source code into small, manageable pieces each of which performs some specific task, and which can be shared somehow, and tested, maintained, and deployed individually. For example, a programmer might define a seri...
Markdown
hhvm/hphp/hack/manual/hack/02-source-code-fundamentals/37-namespaces.md
A ***namespace*** is a container for a set of (typically related) definitions of classes, interfaces, traits, functions, and constants. When the same namespace is declared across multiple scripts, and those scripts are combined into the same program, the resulting namespace is the union of all of the namespaces' indiv...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/01-introduction.md
When combined, operators evaluate according to their associativity. For more information, see [Operator Precedence](/hack/expressions-and-operators/operator-precedence). ## Assignment Operators * [Assignment](/hack/expressions-and-operators/assignment) (`=`, `+=`, and more) * [Coalescing Assignment](/hack/expressions-...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/07-operator-precedence.md
The precedence of Hack operators is shown in the table below. Operators higher in the table have a higher precedence (binding more tightly). Binary operators on the same row are evaluated according to their associativity. Operator | Description | Associativity ------------ | --------- | --------- `\` | [Namespace sep...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/09-echo.md
This intrinsic function converts the value of an expression to `string` (if necessary) and writes the string to standard output. For example: ```Hack $v1 = true; $v2 = 123.45; echo '>>'.$v1.'|'.$v2."<<\n"; // outputs ">>1|123.45<<" $v3 = "abc{$v2}xyz"; echo "$v3\n"; ``` For a discussion of value substitution in str...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/10-exit.md
This intrinsic function terminates the current script, optionally specifying an *exit value* that is returned to the execution environment. For example: ```Hack exit ("Closing down\n"); exit (1); ``` If the exit value is a string, that string is written out. If the exit value is an integer, that represents the scrip...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/12-invariant.md
This intrinsic function behaves like a function with a `void` return type. It is intended to indicate a programmer error for a condition that should never occur. For example: ```Hack no-extract invariant($obj is B, "Object must have type B"); invariant(!$p is null, "Value can't be null"); $max = 100; invariant(!$p is...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/13-list.md
`list()` is special syntax for unpacking tuples. It looks like a function, but it isn't one. It can be used in positions that you would assign into. ```Hack $tuple = tuple('one', 'two', 'three'); list($one, $two, $three) = $tuple; echo "1 -> {$one}, 2 -> {$two}, 3 -> {$three}\n"; ``` The `list()` will consume the `tu...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/21-new.md
The `new` operator allocates memory for an object that is an instance of the specified class. The object is initialized by calling the class's [constructor](../classes/constructors.md) passing it the optional argument list, just like a function call. If the class has no constructor, the constructor that class inherits...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/25-subscript.md
The subscript operator, `[...]` is used to designate an element of a string, a vec, a dict, or a keyset. The element key is designated by the expression contained inside the brackets. For a string or vec, the key must have type `int`, while dict and keyset also allow `string`. The type and value of the result is the ty...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/29-member-selection.md
The operator `->` is used to access instance properties and instance methods on objects. ```Hack file:intbox.hack class IntBox { private int $x; public function __construct(int $x) { $this->x = $x; // Assigning to property. } public function getX(): int { return $this->x; // Accessing property. } }...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/33-scope-resolution.md
When the left-hand operand of operator `::` is an enumerated type, the right-hand operand must be the name of an enumeration constant within that type. For example: ```Hack enum ControlStatus: int { Stopped = 0; Stopping = 1; Starting = 2; Started = 3; } function main(ControlStatus $p1): void { switch ($p1...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/37-incrementing-and-decrementing.md
Hack provides `++` and `--` syntax for incrementing and decrementing numbers. The following are equivalent: ```Hack no-extract $i = $i + 1; $i += 1; $i++; ++$i; ``` Similarly for decrement: ```Hack no-extract $i = $i - 1; $i -= 1; $i--; --$i; ``` This is typically used in for loops: ```Hack for ($i = 1; $i <= 10;...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/47-error-control.md
The operator `@` suppresses any error messages generated by the evaluation of the expression that follows it. For example: ```Hack $infile = @fopen("NoSuchFile.txt", 'r'); ``` On open failure, the value returned by `fopen` is `false`, which you can use to handle the error. There is no need to have any error message ...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/49-casting.md
Casts in Hack convert values to different types. To assert a type without changing its value, see [type assertions](type-assertions.md). ``` Hack (float)1; // 1.0 (int)3.14; // 3, rounds towards zero (bool)0; // false (string)false; // "" ``` Casts are only supported for `bool`, `int`, `float` and `string`. See [ty...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/51-await.md
`await` suspends the execution of an async function until the result of the asynchronous operation represented by the expression that follows this keyword, is available. See [awaitables](../asynchronous-operations/awaitables.md) for details of `await`, and [async](../asynchronous-operations/introduction.md) for a gene...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/52-type-assertions.md
Hack provides the `is` and `as` operators for inspecting types at runtime. To convert primitive types, see [casting](casting.md). The type checker also understands `is` and `as`, so it will infer precise types. ## Checking Types with `is` The `is` operator checks whether a value has the type specified, and returns a...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/58-arithmetic.md
Hack provides the standard arithmetic operators. These only operate on numeric types: `int` or `float`. ## Addition The operator `+` produces the sum of its operands. If both operands have type `int`, the result is `int`. Otherwise, the operands are converted to `float` and the result is `float`. ```Hack -10 + 100;...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/69-string-concatenation.md
The binary operator `.` creates a string that is the concatenation of the left-hand operand and the right-hand operand, in that order. If either or both operands have types other than `string`, their values are converted to type `string`. Consider the following example: ```Hack "foo"."bar"; // "foobar" ``` Here are s...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/70-bitwise-operators.md
Hack provides a range of bitwise operators. These assume that their operands are `int`. ## Bitwise AND The operator `&` performs a bitwise AND on its two `int` operands and produces an `int`. For example: ```Hack 0b101111 & 0b101; // result is 0b101 $lcase_letter = 0x73; // ...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/72-logical-operators.md
Hack provides the conventional boolean operations. ## Logical AND `&&` The operator `&&` calculates the boolean AND operation of its two operands. ```Hack no-extract if (youre_happy() && you_know_it()) { clap_your_hands(); } ``` If either operand does not have a boolean type, it is converted to a boolean first. T...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/75-comparisons.md
Hack provides comparison operators. They operate on two operands and return `bool`. * `<`, which represents *less-than* * `>`, which represents *greater-than* * `<=`, which represents *less-than-or-equal-to* * `>=`, which represents *greater-than-or-equal-to* The type of the result is `bool`. Comparison operators ar...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/77-equality.md
There are two equality operators in Hack: `===` (recommended) and `==`. They also have not-equal equivalents, which are `!==` and `!=`. ```Hack 1 === 2; // false 1 !== 2; // true ``` ## `===` Equality `===` compares objects by reference. ```Hack file:object.hack class MyObject {} ``` ```Hack file:object.hack $obj ...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/89-ternary.md
The ternary operator `?` `:` is a shorthand for `if` statements. It is an expression, so it evaluates to a value. For example: ```Hack no-extract $days_in_feb = is_leap_year($year) ? 29 : 28; ``` It takes three operands `e1 ? e2 : e3`. If `e1` evaluates to a truthy value, then the result is the evaluation of `e2`. Ot...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/91-coalesce.md
Given the expression `e1 ?? e2`, if `e1` is defined and not `null`, then the result is `e1`. Otherwise, `e2` is evaluated, and its value becomes the result. There is a sequence point after the evaluation of `e1`. ```Hack $nully = null; $nonnull = 'a string'; \print_r(vec[ $nully ?? 10, // 10 as $nully is `null` ...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/93-pipe.md
The binary pipe operator, `|>`, evaluates the result of a left-hand expression and stores the result in `$$`, the pre-defined pipe variable. The right-hand expression *must* contain at least one occurrence of `$$`. ## Basic Usage With the pipe operator, you can chain function calls, as shown in the code below. ``` Ha...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/97-assignment.md
The assignment operator `=` assigns the value of the right-hand operand to the left-hand operand. For example: ```Hack $a = 10; ``` ## Element Assignment We can assign to array elements, as follows: ```Hack $v = vec[1, 2, 3]; $v[0] = 42; // $v is now vec[42, 2, 3] $v = dict[0 => 10, 1 => 20, 2 => 30]; $v[1] = 22...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/98-yield.md
Any function containing the `yield` operator is a *generator function*. A generator function generates a collection of zero or more key/value pairs where each pair represents the next element in some series. For example, a generator might yield random numbers or the series of Fibonacci numbers. When a generator functio...
Markdown
hhvm/hphp/hack/manual/hack/03-expressions-and-operators/99-XHP-attribute-selection.md
When working with [XHP](/hack/XHP/introduction), use the `->:` operator to retrieve an XHP class [attribute](/hack/XHP/basic-usage#attributes) value. The operator can also be used on arbitrary expressions that resolve to an XHP object (e.g. `$a ?? $b)->:`). ```Hack no-extract use namespace Facebook\XHP\Core as x; fi...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/01-introduction.md
**Topics covered in this section** * [break/continue](/hack/statements/break-and-continue) * [do/while](/hack/statements/do) * [for](/hack/statements/for) * [foreach](/hack/statements/foreach) * [if/else if/else](/hack/statements/if) * [return](/hack/statements/return) * [switch](/hack/statements/switch) * [throw/try/...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/02-break-and-continue.md
## `continue` A `continue` statement terminates the execution of the innermost enclosing `do`, `for`, `foreach`, or `while` statement. For example: ```Hack for ($i = 1; $i <= 10; ++$i) { if (($i % 2) === 0) { continue; } echo "$i is odd\n"; } ``` Although a `continue` statement must not attempt to break o...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/03-do.md
The general format of a `do` statement is `do` *statement* `while (` *expression* `);` The *single* statement is executed. If the expression tests `true`, the process is repeated. If the expression tests `false`, control transfers to the point immediately following the end of the `do` statement. The loop body (that ...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/04-for.md
The `for` statement is typically used to step through a range of values in ascending or descending increments, performing some set of operations on each value. For example: ```Hack for ($i = 1; $i <= 5; ++$i) { echo "$i\t".($i * $i)."\n"; // output a table of squares } $i = 1; for (; $i <= 5; ) { echo "$i\t".($i...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/05-foreach.md
The `foreach` statement iterates over the set of elements in a given collection, starting at the beginning, executing a single statement each iteration. On each iteration, the value of the current element is assigned to the corresponding variable, as specified. The loop body is executed zero or more times. For example:...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/06-if.md
An `if` statement will execute code if a condition is true. If it's false, an `else` block can execute. ```Hack $count = 11; if ($count < 10) { echo "small"; } else if ($count < 20) { echo "medium"; } else { echo "large"; } ``` Conditions must have type `bool` or be implicitly convertible to `bool`. If the c...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/07-return.md
A `return` statement can only occur inside a function, in which case, it causes that function to terminate normally. The function can optionally return a single value (but one which could contain other values, as in a tuple, a shape, or an object of some user-defined type), whose type must be compatible with the funct...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/08-switch.md
A `switch` statement typically consists of a controlling expression, some case labels, and optionally a default label. Based on the value of the controlling expression, execution passes to one of the case labels, the default label, or to the statement immediately following the switch statement. For example: ```Hack ...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/09-try.md
An *exception* is some unusual condition in that it is outside the ordinary expected behavior. (Examples include dealing with situations in which a critical resource is needed, but is unavailable, and detecting an out-of-range value for some computation.) As such, exceptions require special handling. Whenever some exc...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/10-use.md
The `use` statement permits names defined in one namespace to be introduced into another namespace, so they can be referenced there by their simple name rather than their (sometimes very long) fully qualified name. The `use` statement can only be present at the top level. Consider the following: ```Hack file:use.hack...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/11-using.md
A `using` statement is used to enforce [object disposal](../classes/object-disposal.md). It has two forms: block and non-block. Here is an example of the block form: ```Hack no-extract using ($f1 = new TextFile("file1.txt", "rw")) { // ... work with the file } // __dispose is called here ``` The type of the ...
Markdown
hhvm/hphp/hack/manual/hack/04-statements/12-while.md
The general format of a `while` statement is `while (` *expression* ` )` *statement* If the expression tests `true`, the *single* statement that follows is executed, and the process is repeated. If the expression tests `false`, control transfers to the point immediately following the end of the `while` statement. ...
Markdown
hhvm/hphp/hack/manual/hack/05-functions/01-introduction.md
The `function` keyword defines a global function. ```Hack function add_one(int $x): int { return $x + 1; } ``` The `function` keyword can also be used to define [methods](/hack/classes/methods). ## Default Parameters Hack supports default values for parameters. ```Hack function add_value(int $x, int $y = 1): int...
Markdown
hhvm/hphp/hack/manual/hack/05-functions/02-anonymous-functions.md
Hack supports anonymous functions. In the example below, the anonymous function, `$f`, evaluates to a function that returns the value of `$x + 1`. ``` Hack $f = $x ==> $x + 1; $two = $f(1); // result of 2 ``` To create an anonymous function with more than one parameter, surround the parameter list with parentheses:...
Markdown
hhvm/hphp/hack/manual/hack/05-functions/03-type-enforcement.md
HHVM does a runtime type check for function arguments and return values. ```Hack error function takes_int(int $_): void {} function check_parameter(): void { takes_int("not an int"); // runtime error. } function check_return_value(): int { return "not an int"; // runtime error. } ``` If a type is wrong, HHVM wi...
Markdown
hhvm/hphp/hack/manual/hack/05-functions/05-format-strings.md
The Hack typechecker checks that format strings are being used correctly. ## Quickstart ```Hack error // Correct. Str\format("First: %d, second: %s", 1, "foo"); // Typechecker error: Too few arguments for format string. Str\format("First: %d, second: %s", 1); ``` This requires that the format string argument is a s...
Markdown
hhvm/hphp/hack/manual/hack/05-functions/20-inout-parameters.md
Hack functions normally pass arguments by value. `inout` provides "copy-in, copy-out" arguments, which allow you to modify the variable in the caller. ```Hack function takes_inout(inout int $x): void { $x = 1; } function call_it(): void { $num = 0; takes_inout(inout $num); // $num is now 1. } ``` This is si...
Markdown
hhvm/hphp/hack/manual/hack/05-functions/30-function-references.md
It is often useful to refer to a function (or a [method](https://docs.hhvm.com/hack/classes/methods)) without actually calling it&mdash;for example, as an argument for functions like `Vec\map`. **Note:** The following syntax is only supported since HHVM 4.79. For older HHVM versions, see [old syntax](#old-syntax) belo...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/01-introduction.md
Classes provide a way to group functionality and state together. To define a class, use the `class` keyword. ```Hack class Counter { private int $i = 0; public function increment(): void { $this->i += 1; } public function get(): int { return $this->i; } } ``` To create an instance of a class, use...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/03-methods.md
A method is a function defined in a class. ```Hack file:person.hack class Person { public string $name = "anonymous"; public function greeting(): string { return "Hi, my name is ".$this->name; } } ``` To call an instance method, use `->`. ```Hack file:person.hack $p = new Person(); echo $p->greeting(); ``...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/05-properties.md
A property is a variable defined inside a class. ```Hack file:intbox.hack class IntBox { public int $value = 0; } ``` Instance properties are accessed with `->`. Every instance has a separate value for an instance property. ```Hack file:intbox.hack $b = new IntBox(); $b->value = 42; ``` Note that there is no `$` ...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/06-inheritance.md
Hack supports single inheritance between classes. ``` Hack class IntBox { public function __construct(protected int $value) {} public function get(): int { return $this->value; } } class MutableIntBox extends IntBox { public function set(int $value): void { $this->value = $value; } } ``` Classes c...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/16-constructors.md
A constructor is a specially named instance method that is used to initialize the instance immediately after it has been created. A constructor is called by the [`new` operator](../expressions-and-operators/new.md). For example: ```Hack class Point { private static int $pointCount = 0; // static property with init...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/18-constants.md
A class can contain definitions for named constants. Because a class constant belongs to the class as a whole, it is implicitly `static`. For example: ```Hack class Automobile { const DEFAULT_COLOR = "white"; // ... } <<__EntryPoint>> function main(): void { $col = Automobile::DEFAULT_COLOR; // or: $col = self...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/19-type-constants.md
Type constants provide a way to abstract a type name. However, type constants only make sense in the context of interfaces and inheritance hierarchies, so they are discussed under those topics. For now, the declaration of a type constant involves the keywords `const type`. Without explanation, here's an example: ``...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/21-object-disposal.md
Modern programming languages allow resources to be allocated at runtime, under programmer control. However, in the case where explicit action must be taken to free such resources, different languages have different approaches. Some languages use a *destructor* for cleanup, while others use a *finalizer*, which is calle...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/31-type-constants-revisited.md
Imagine that you have a class, and some various `extends` to that class. ```Hack abstract class User { public function __construct(private int $id) {} public function getID(): int { return $this->id; } } trait UserTrait { require extends User; } interface IUser { require extends User; } class AppUser ...
Markdown
hhvm/hphp/hack/manual/hack/06-classes/33-methods-with-predefined-semantics.md
If a class contains a definition for a method having one of the following names, that method must have the prescribed visibility, signature, and semantics: Method Name | Description ------------|------------- [`__construct`](constructors.md) | A constructor [`__dispose`](#method-__dispose) | Performs object-cleanu...
Markdown
hhvm/hphp/hack/manual/hack/07-traits-and-interfaces/01-introduction.md
**Topics covered in this section** * [Using a Trait](using-a-trait.md) * [Implementing an Interface](implementing-an-interface.md) * [Trait and Interface Requirements](trait-and-interface-requirements.md)
Markdown
hhvm/hphp/hack/manual/hack/07-traits-and-interfaces/02-implementing-an-interface.md
A class can implement a *contract* through an interface, which is a set of required method declarations and constants. Note that the methods are only declared, not defined; that is, an interface defines a type consisting of *abstract* methods, where those methods are implemented by client classes as they see fit. An i...
Markdown
hhvm/hphp/hack/manual/hack/07-traits-and-interfaces/03-using-a-trait.md
Traits are a mechanism for code reuse that overcomes some limitations of Hack single inheritance model. In its simplest form a trait defines properties and method declarations. A trait cannot be instantiated with `new`, but it can be _used_ inside one or more classes, via the `use` clause. Informally, whenever a tra...
Markdown
hhvm/hphp/hack/manual/hack/07-traits-and-interfaces/04-trait-and-interface-requirements.md
Trait and interface requirements allow you to restrict the use of these constructs by specifying what classes may actually use a trait or implement an interface. This can simplify long lists of `abstract` method requirements, and provide a hint to the reader as to the intended use of the trait or interface. ## Syntax ...
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/01-introduction.md
Hack includes diverse range of array-like data structures. Hack arrays are value types for storing iterable data. The types available are [`vec`](/hack/arrays-and-collections/vec-keyset-and-dict#vec), [`dict`](/hack/arrays-and-collections/vec-keyset-and-dict#dict) and [`keyset`](/hack/arrays-and-collections/vec-keyset...
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/05-vec-keyset-and-dict.md
`vec`, `keyset` and `dict` are value types. Any mutation produces a new value, and does not modify the original value. These types are referred to as 'Hack arrays'. Prefer using these types whenever you're unsure. ## `vec` A `vec` is an ordered, iterable data structure. It is created with the `vec[]` syntax. ```Hac...
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/10-object-collections.md
The collection object types are `Vector`, `ImmVector`, `Map`, `ImmMap`, `Set`, `ImmSet` and `Pair`. There are also a range of helper interfaces, discussed below. Hack Collection types are objects. They have reference semantics, so they can be mutated. Collections define a large number of methods you can use. They als...
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/15-varray-and-darray.md
**`varray`, `darray` and `varray_or_darray` are legacy value types for storing iterable data.**. They are also called 'PHP arrays' and will eventually be removed. PHP arrays are immutable value types, just like Hack arrays. Unlike Hack arrays, they include legacy behaviors from PHP that can hide bugs. For example, in...
Markdown
hhvm/hphp/hack/manual/hack/08-arrays-and-collections/20-mutating-values.md
Hack arrays are value types. This makes your code easier to reason about, faster (no work required on a fresh web request), and well suited for caches. If you really need mutation, Hack provides you with several options. ## Updating value types Updating an element in a value type creates a new copy. ``` Hack functi...
Markdown
hhvm/hphp/hack/manual/hack/10-types/01-introduction.md
Hack includes a strong static type system. This section covers the basic features of the type checker. See also the [`is` operator](../expressions-and-operators/is.md) for checking the type of a value, and the [`as` operator](../expressions-and-operators/as.md) for asserting types. **Topics covered in this section** ...
Markdown
hhvm/hphp/hack/manual/hack/10-types/45-soft-types.md
A soft type hint `<<__Soft>> Foo` allows you to add types to code without crashing if you get the type wrong. ```Hack function probably_int(<<__Soft>> int $x): @int { return $x + 1; } function definitely_int(int $x): int { return $x + 1; } ``` Calling `definitely_int("foo")` will produce an error at runtime, whe...
Markdown
hhvm/hphp/hack/manual/hack/10-types/46-generic-types.md
Hack contains a mechanism to define generic&mdash;that is, type-less&mdash;classes, interfaces, and traits, and to create type-specific instances of them via type parameters. Consider the following example in which `Stack` is a generic class having one type parameter, `T`, and that implements a stack: ```Hack file:st...
Markdown
hhvm/hphp/hack/manual/hack/10-types/67-nullable-types.md
A type `?Foo` is either a value of type `Foo`, or `null`. ``` Hack function takes_nullable_str(?string $s): string { if ($s is null){ return "default"; } else { return $s; } } ``` `nonnull` is any value except `null`. You can use it to check if a value is not `null`: ``` Hack function takes_nullable_st...
Markdown
hhvm/hphp/hack/manual/hack/10-types/76-type-conversion.md
In a few situations (documented in the following sections) the values of operands are implicitly converted from one type to another. Explicit conversion is performed using the [cast operator](../expressions-and-operators/casting.md). If an expression is converted to its own type, the type and value of the result are t...
Markdown
hhvm/hphp/hack/manual/hack/10-types/79-type-aliases.md
We can create an alias name for a type, and it is common to do so for non-trivial tuple and shape types. Once such a type alias has been defined, that alias can be used in almost all contexts in which a type specifier is permitted. Any given type can have multiple aliases, and a type alias can itself have aliases. #...
Markdown
hhvm/hphp/hack/manual/hack/10-types/82-supertypes-and-subtypes.md
The set of built-in and user-defined types in Hack can be thought of as a type hierarchy of *supertypes* and *subtypes* in which a variable of some type can hold the values of any of its subtypes. For example, `int` and `float` are subtypes of `num`. A supertype can have one or more subtypes, and a subtype can have on...
Markdown
hhvm/hphp/hack/manual/hack/10-types/85-type-refinement.md
A supertype has one or more subtypes, and while any operation permitted on a value of some supertype is also permitted on a value of any of its subtypes, the reverse is not true. For example, the type `num` is a supertype of `int` and `float`, and while addition and subtraction are well defined for all three types, bit...
Markdown
hhvm/hphp/hack/manual/hack/10-types/86-with-refinement.md
Besides `is`-expressions, Hack supports another form of type refinements, which we refer to as `with`-refinements in this section. This feature allows more precise typing of classes/interfaces/traits in a way that specific _type_ or _context_ constant(s) are more specific (i.e., refined). For example, given the defini...
Markdown
hhvm/hphp/hack/manual/hack/10-types/88-type-inferencing.md
While certain kinds of variables must have their type declared explicitly, others can have their type inferred by having the implementation look at the context in which those variables are used. For example: ```Hack function foo(int $i): void { $v = 100; } ``` As we can see, `$v` is implicitly typed as `int`, an...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/01-introduction.md
This section covers the different built-in types available in Hack. ## Primitive Types Hack has the following primitive types: [bool](/hack/built-in-types/bool), [int](/hack/built-in-types/int), [float](/hack/built-in-types/float), [string](/hack/built-in-types/string), and [null](/hack/built-in-types/null). ## Union...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/04-bool.md
The Boolean type `bool` can store two distinct values, which correspond to the Boolean values `true` and `false`, respectively. Consider the following example: ```Hack function is_leap_year(int $yy): bool { return ((($yy & 3) === 0) && (($yy % 100) !== 0)) || (($yy % 400) === 0); } <<__EntryPoint>> function main()...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/07-int.md
The integer type `int` is signed and uses twos-complement representation for negative values. At least 64 bits are used, so the range of values that can be stored is at least [-9223372036854775808, 9223372036854775807]. Namespace HH\Lib\Math contains the following integer-related constants: `INT64_MAX`, `INT64_MIN`, `...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/10-float.md
The floating-point type, `float`, allows the use of real numbers. It supports at least the range and precision of IEEE 754 64-bit double-precision representation, and includes the special values minus infinity, plus infinity, and Not-a-Number (NaN). Using predefined constant names, those values are written as `-INF`, ...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/13-num.md
The type `num` can represent any `int` or `float` value. This type can be useful when specifying the interface to a function. Consider the following function declarations from the math library: ```Hack no-extract function sqrt(num $arg): float; function log(num $arg, ?num $base = null): float; function abs<T as num>(T...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/16-string.md
A `string` is a sequence of *bytes* - they are not required to be valid characters in any particular encoding, for example, they may contain null bytes, or invalid UTF-8 sequences. # Basic operations Concatenation and byte indexing are built-in operations; for example: - `"foo"."bar"` results in `"foobar"` - `"abc"[...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/19-void.md
The type `void` indicates the absence of a value. It is used to declare that a function does *not* return any value. As such, a void function can contain one or more `return` statements, provided none of them return a value. Consider the following example: ```Hack function draw_line(Point $p1, Point $p2): void { /* ....
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/25-tuples.md
Suppose we wish to have a function return multiple values. We can do that by using a tuple containing two or more elements. A tuple is an *ordered* set of one or more elements, which can have different types. The number of elements in a particular tuple is fixed when that tuple is created. After a tuple has been create...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/28-shape.md
A shape is a lightweight type with named fields. It's similar to structs or records in other programming languages. ```Hack $my_point = shape('x' => -3, 'y' => 6, 'visible' => true); ``` ## Shape Values A shape is created with the `shape` keyword, with a series of field names and values. ``` Hack $server = shape('n...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/31-arraykey.md
The type `arraykey` can represent any integer or string value. For example: ```Hack function process_key(arraykey $p): void { if ($p is int) { // we have an int } else { // we have a string } } ``` Values of array or collection type can be indexed by `int` or `string`. Suppose, for example, an operatio...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/34-enum.md
Use an enum (enumerated type) to create a set of named, constant, immutable values. In Hack, enums are limited to `int` or `string` (as an [`Arraykey`](/hack/built-in-types/arraykey)), or other `enum` values. ## Quickstart To access an enum's value, use its full name, as in `Colors::Blue` or `Permission::Read`. ```H...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/35-enum-class.md
In comparison to [enumerated types (enums)](/hack/built-in-types/enum), enum classes are not restricted to int and string values. ## Enum types v. Enum class Built-in enum types limit the base type of an enum to `arraykey` -- an integer or string -- or another enum. The base type of an _enum class_ can be any type: t...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/36-enum-class-label.md
## Values v. Bindings With [enum types](/hack/built-in-types/enum) and [enum classes](/hack/built-in-types/enum-class), most of the focus is given to their values. Expressions like `E::A` denote the value of `A` in `E`, but the fact that `A` was used to access it is lost. ```Hack enum E: int { A = 42; B = 42; } ...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/49-this.md
The type name `this` refers to *the current class type at run time*. As such, it can only be used from within a class, an interface, or a trait. (The type name `this` should not be confused with [`$this`](../source-code-fundamentals/names.md), which refers to *the current instance*, whose type is `this`.) For example:...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/55-classname.md
For the most part, we deal with class types directly via their names. For example: ```Hack no-extract class Employee { // ... } $emp = new Employee(); ``` However, in some applications, it is useful to be able to abstract a class' name rather than to hard-code it. Consider the following: ```Hack file:employee.h...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/56-darray-varray-runtime-options.md
As of [HHVM 4.103](https://hhvm.com/blog/2021/03/31/hhvm-4.103.html), `darray` / `varray` are aliased to `dict` / `vec` respectively. Use [Hack arrays](/hack/arrays-and-collections/hack-arrays). ## WARNING WARNING WARNING _These runtime options are a migrational feature. This means that they come and go when new hhvm...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/58-resources.md
A resource is a descriptor to some sort of external entity. (Examples include files, databases, and sockets.) Resources are only created or consumed by the implementation; they are never created or consumed by Hack code. Each distinct resource has a unique ID of some unspecified form. When scripts execute in a mode ha...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/61-null.md
The `null` type has only one possible value, the value `null`. You can use the `null` type when refining with `is`. ```Hack function number_or_default(?int $x): int { if ($x is null) { return 42; } else { return $x; } } ``` See [nullable types](../types/nullable-types.md) for a discussion of `?T` types...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/70-mixed.md
The `mixed` type represents any value at all in Hack. For example, the following function can be passed anything. ```Hack no-extract function takes_anything(mixed $m): void {} function call_it(): void { takes_anything("foo"); takes_anything(42); takes_anything(new MyClass()); } ``` `mixed` is equivalent to `?...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/71-dynamic.md
**This type is intended to help with code being transitioned from untyped mode to strict mode.** Although `dynamic` can be used as the type of a class constant or property, or a function return type, its primary use is as a parameter type. This special type is used to help capture dynamism in the existing codebase in...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/73-noreturn.md
A function that never returns a value can be annotated with the `noreturn` type. A `noreturn` function either loops forever, throws an an error, or calls another `noreturn` function. ```Hack function something_went_wrong(): noreturn { throw new Exception('something went wrong'); } ``` `invariant_violation` is an ex...
Markdown
hhvm/hphp/hack/manual/hack/11-built-in-types/74-nothing.md
The type `nothing` is the bottom type in the Hack typesystem. This means that there is no way to create a value of the type `nothing`. `nothing` only exists in the typesystem, not in the runtime. The concept of a bottom type is quite difficult to grasp, so I'll first compare it to the supertype of everything `mixed`. ...
Markdown
hhvm/hphp/hack/manual/hack/12-generics/01-introduction.md
Certain types (classes, interfaces, and traits) and their methods can be *parameterized*; that is, their declarations can have one or more placeholder names---called *type parameters*---that are associated with types via *type arguments* when a class is instantiated, or a method is called. A type or method having such ...