Web Development With HHVM and Hack 17: Types and Null

Mike Abelar
2 min readApr 28, 2020

--

In the last tutorial, we went over traits: https://medium.com/@mikeabelar/web-development-with-hhvm-and-hack-16-classes-part-6-traits-b076b4f8643. In this tutorial, we will cover types and null.

What Are Types?

Types are used mainly in classes and functions to define what kind of variable the class or function is dealing with. For example, in the following function definition:

function add_two_numbers(int $one, int $two) : int

$one and $two are integers (denoted as int) and the return type is int . int is a type. Types provide guarantees to the function or to the class about the input and the output.

Another example of types is properties in a class:

class Person {
private string $name;
...
}

Here, we use the string keyword to indicate that name is a string.

You can find the full list of types in Hack here: https://docs.hhvm.com/hack/built-in-types/introduction

Null Types

One type that is of importance is the null type. Null means that the variable represents nothing. There are numerous cases in which this can arise. For one, maybe the call to a function did not complete successfully and so you get a null output. The second, more common reason one might see null is when a function takes an optional argument. An optional argument means that the function’s argument may be null or non-null. Let us take a look at an example:

// this function takes in a name and optionally an age
function say_name_and_age(string $name, ?int $age = null) : void {
print("Name is ".$name."\n");
// check if age is null
// this is important. Do not want to print null
if (!($age is null)) {
print("Age is ".$age."\n");
}
}
<<__EntryPoint>>
function main(): noreturn {
// example of both params
say_name_and_age("Bob", 40);
// example of just one param
say_name_and_age("Alice");
exit(0);
}

When run, the code outputs:

Name is Bob
Age is 40
Name is Alice

As we can see from the main function, we make one function call with two parameters and one function call with one parameter. Looking at the function declaration:

function say_name_and_age(string $name, ?int $age = null)

?int is used to represent a type that is an int or it is null. We call this type nullable. Meaning, it can be null. We also define a default value for the variable: $age = null . Therefore, if we do not specify the parameter, then the parameter becomes null, which is allowed because we use the nullable type.

Finally, to check if a parameter is not null we use if (!($age is null)) which means if age is not null. To check for null, we use the is keyword. is is used to check the type of a variable.

In the next tutorial, we cover mixed: https://medium.com/@mikeabelar/web-development-with-hhvm-and-hack-18-mixed-74de23700f78

--

--