Constructor/Destructor

Constructor

The constructor syntax in THP is inspired by Kotlin.

Constructors are declared like function definitions:

//          |this is the constructor |
class Animal(String fullname, Int age)

// Creating an instance
val cat = Animal("Michi", 3)thp

A constructor declared that way is public.

Note that the parameters in the constructor (fullname, age above) are not properties, and cannot be used inside the class methods, only in the init block and properties declaration.

To declare properties in the constructor see Constructor promotion.

Constructor visibility

If you want to declare a constructor as protected or private you need to add the constructor keyword, after the visibility modifier:

// Cow has a protected constructor
class Cow
protected constructor(String color)

// Bat has a private constructor
class Bat
private constructor(Int height)thp

Init block

The init block allow us to run code during the construction of the instance:

class Dog(String name) {
  pub String name = name
  Int name_len = name.length

  init {
      print("Dog created: {name}")
  }

}thp

This would be equilavent to the following PHP code:

class Dog {
    public string $name;
    private int $name_len;

    public function __construct(string $name) {
        $this->name = $name;
        $this->name_len = size($name);
        print("Dog created: $name");
    }
}

Constructor promotion

Constructor parameters can serve as class properties. This is done by adding a modifier and var/val.

class Parrot(
  // A public property
  pub val String name,
  // A protected property
  protected var Int age,
  // A private property
  var String last_name,
)thp

By using this syntax you are declaring properties and assigning them at the same time.

The contructor parameters can also have default values.

Derived properties

You can declare properties whose values depend on values on the constructor.

class Animal(
  val String fullname,
)
{
  // A property whose value depends on `fullname`
  // This is executed after the contructor
  pub val Int name_length = fullname.length
}

val a2 = Animal("Doa")
print(a2.name_length) //: 3thp

Constructor that may fail

A constructor may only fail if there is code that can fail on the init block.

TBD

Proposal 1:

class PrayingMantis(String name)
throws Error {
  init -> Error! {
      // Initialization code that may fail
  }
}thp

Destructor

The destructor in THP is the same as PHP.

class Owl() {
  pub fun __destruct() {
      // Cleanup
      print("Destroying Owl...")
  }
}thp