Catchable fatal error: Hack type error
Catchable fatal error: Hack type error
示例来自 presentation 第 31 页
class Foo<T> {
public function add(T $delta): Foo {
$this->num += $delta; // line 6
return $this;
}
public function get(): T {
return $this->num;
}
public function __construct(private T $num): void {}
}
$f1 = new Foo(123);
$f1->add(567);
echo $f1->get(), PHP_EOL;
$f2 = new Foo(1.23);
echo $f2->add(5.67)->get(), PHP_EOL;
错误
Catchable fatal error: Hack type error: Typing error at example.php line 6
有什么问题?
HipHop VM 3.11.1(相对)
编译器:tags/HHVM-3.11.1-0-g64d37362bc0b6aee919492ad61cf65ce0a5d5e92
回购架构:8b80ba45250a6669cd610c189dbbb55b6218c2a3
如果您 运行 类型检查器 (hh_client
),您将收到如下错误:
This is a num because this is used in an arithmetic operation. It is incompatible with a value of generic type T
这是因为+
运算符要求两边都是num类型,而T
可以是任意类型
您可以将 constraint 添加到 T
,这样它就必须是 num
(class Foo<T as num>
),或者您可以只使用 num
作为类型而不是泛型 T
.
使用num
将允许您在同一个实例中混合使用浮点数和整数。使用约束,一个实例只能使用浮点数或整数,但不能同时使用两者。
示例来自 presentation 第 31 页
class Foo<T> {
public function add(T $delta): Foo {
$this->num += $delta; // line 6
return $this;
}
public function get(): T {
return $this->num;
}
public function __construct(private T $num): void {}
}
$f1 = new Foo(123);
$f1->add(567);
echo $f1->get(), PHP_EOL;
$f2 = new Foo(1.23);
echo $f2->add(5.67)->get(), PHP_EOL;
错误
Catchable fatal error: Hack type error: Typing error at example.php line 6
有什么问题?
HipHop VM 3.11.1(相对)
编译器:tags/HHVM-3.11.1-0-g64d37362bc0b6aee919492ad61cf65ce0a5d5e92
回购架构:8b80ba45250a6669cd610c189dbbb55b6218c2a3
如果您 运行 类型检查器 (hh_client
),您将收到如下错误:
This is a num because this is used in an arithmetic operation. It is incompatible with a value of generic type T
这是因为+
运算符要求两边都是num类型,而T
可以是任意类型
您可以将 constraint 添加到 T
,这样它就必须是 num
(class Foo<T as num>
),或者您可以只使用 num
作为类型而不是泛型 T
.
使用num
将允许您在同一个实例中混合使用浮点数和整数。使用约束,一个实例只能使用浮点数或整数,但不能同时使用两者。