Search code examples
hacklang

Self/child static construct (hacklang)


Guess it's impossible design for Hacklang?

<?hh //strict

 abstract class Foo {

    public static function bar():void {

        $class = get_called_class();
        $instance = new $class();

        // do stuff

    }
}

Can't use new on classname 'Foo'; __construct arguments are not guaranteed to be consistent in child classes (Typing[4060])


Solution

  • You need to annotate your class with <<__ConsistentConstruct>> -- since you can change the signature of the constructor in subclasses by default, the instantiation would be unsafe otherwise, since the argument list could have changed. You can read more either from the official documentation or in this blog post I wrote giving a bit more of a narrative around the feature.

    As an aside, you can replace

    $class = get_called_class();
    $instance = new $class();
    

    with the much nicer

    $instance = new static();