Web Development With HHVM and Hack 15: Classes Part 5: Static
In the last tutorial, we covered generics: https://medium.com/@mikeabelar/web-development-with-hhvm-and-hack-14-classes-part-4-f97851b1023c. In this tutorial, we will cover the use of the static
keyword with classes.
What is Static?
Static functions in classes do not reference the state of a class instance. To illustrate this distinction, first consider a class that contains information about a person. The class stores the person’s name as an instance variable. Below is an illustration of the class along with code that calls the class functions:
class Person {
private string $name;
public function __construct(string $n) {
$this->name = $n;
} public function sayName() : void {
print("My name is " . $this->name . "\n");
}
}<<__EntryPoint>>
function main() : noreturn {
$person = new Person("Bob");
$person->sayName();
exit(0);
}
Upon running the code, we get the following output:
My name is Bob
This code should not be new to us. However, I would like to point out that the sayName
function uses the instance variable of name
. In other words, the instance of the class specifies the name
variable. Therefore, that instance of the class is said to have an instance variable as the value of the variable is tied to the instance of the class.
Now, let us explore static functions. As mentioned before, static functions cannot use any instance variables (so we cannot call $this
inside a static function). The idea of static functions is that all information should be passed in as parameters. Let us take a look of a static version of our class:
class Person {
// notice the name static
// we now pass in the data
public static function sayName(string $name) : void {
print("My name is " . $name . "\n");
}
}<<__EntryPoint>>
function main() : noreturn {
// notice the way to call static functions
Person::sayName("Bob");
exit(0);
}
If we run the code, we get the same exact output.
Here are a few things to note:
First, we use the static
keyword when declaring a static function.
Second, as we mentioned above, all data used in a static function should be passed in as arguments (rather than referencing instance variables)
Third, calling a static function requires the use of the name of the class followed by ::
followed by the name of the function.
In the next tutorial, we cover traits: https://medium.com/@mikeabelar/web-development-with-hhvm-and-hack-16-classes-part-6-traits-b076b4f8643