Self/child 静态结构(hacklang)

Self/child static construct (hacklang)

猜猜这是不可能的 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])

您需要用 <<__ConsistentConstruct>> 注释您的 class -- 因为您可以在默认情况下更改子 class 中构造函数的签名,否则实例化将不安全,因为参数列表可能已经改变。您可以从 official documentation or in this blog post I wrote giving a bit more of a narrative around the feature.

阅读更多内容

顺便说一句,你可以替换

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

更漂亮

$instance = new static();