Classes: Defining A Basic Class

A class declaration defines a named-class type, and the data and method members associated with that type. The following kinds of members are permitted:

  • Constants -- the constant values associated with the class.
  • Properties -- the variables of the class or of each instance of that class.
  • Methods -- the computations and actions that can be performed on behalf of the class or on any instance of that class.
  • Constructor -- the actions required to initialize an instance of the class.
  • Type constant -- a way of parameterizing class types without using generics.

Here's an extract from a Point class that supports a two-dimensional Cartesian point:

<?hh // strict

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

class Point {
  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
  }

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

  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(3.4);
  $p3 = new Point();

  /* HH_FIXME[4067] implicit __toString() is now deprecated */
  echo "\$p1 is $p1\n"; // implicit call to __toString()
  /* HH_FIXME[4067] implicit __toString() is now deprecated */
  echo "\$p2 is $p2\n"; //   "          "         "
  /* HH_FIXME[4067] implicit __toString() is now deprecated */
  echo "\$p3 is $p3\n"; //   "          "         "
}
Output
$p1 is (3.4,5.6)
$p2 is (3.4,0)
$p3 is (0,0)

The complete set of members of a class are those specified in its declaration along with the members inherited from its base class, from the interfaces it implements, and from the traits that it uses.

A number of names (such as __construct and __toString) are reserved for methods with required semantics, which user-defined versions must follow. These are described in predefined methods.

Methods and properties can either be static or instance members. A static member is declared using static. An instance member is one that is not static. A static member belongs to the class as a whole, while an instance member applies to a particular instance.