Classes: Methods

A method is a class-specific function belonging to the class as a whole (in which case, it's declared static) or to each instance of that class (in which case, static is absent). Each method has its own visibility. For example:

<?hh // strict

namespace Hack\UserDocumentation\Classes\Methods\Examples\Point;

class Point {
  private static int $pointCount = 0; // static property with initializer
  private float $x;           // instance property
  private float $y;           // instance property

  public function __construct(num $x = 0, num $y = 0) { // instance method
    $this->x = (float)$x;         // access instance property
    $this->y = (float)$y;         // access instance property
    ++Point::$pointCount;           // include new Point in Point count
  }

  public function move(num $x = 0, num $y = 0): void { // instance method
    $this->x = (float)$x;
    $this->y = (float)$y;
  }

  public static function get_point_count(): int { // static method
    return Point::$pointCount;    // access static property
  }

  public function __toString(): string { // instance method
    return '(' . $this->x . ',' . $this->y . ')';
  }
  // ...
}

<<__EntryPoint>>
function main(): void {
  $p1 = new Point(3.4, 5.6);
  $p2 = new Point();
  $p3 = new Point();
  $p2->move(-2.2, -4);
  echo "\$p2 is $p2\n";  // implicit call to __toString()
  echo "The number of Points is " . Point::get_point_count() . "\n";
}
Output
$p2 is (-2.2,-4)
The number of Points is 3

A static method that is visible is callable regardless of whether any instances of its parent class exist. And as we can see, we call get_point_count using the scope-resolution operator, ::, preceded by the class name.

When an instance method such as move is called, the location of the Point on which it was called to operate is passed secretly to the called method inside of which it is available by the reserved name $this. So, to access property $x in the Point referred to by $this, we use the member-selection operator, ->, as in $this->x. We do likewise to access another instance method in that class. (Static methods do not have a $this, so this approach is not used to access a static method, as we can see.)

Consider the case of a public method (such as move) that we wish to access outside a method of its class. As we're not inside the class, no $this is available to us; however, we do have the name of the object containing that method, and we can use that along with the -> operator to select that method, as in $p2->move(-2.2, -4).

The signature of a method is a combination of the parent class name, that method's name, and its parameter types. (Note, however, that Hack does not support method overloading.)