9

我今天开始学习 hacklang,现在我有点卡在形状上:http: //docs.hhvm.com/manual/en/hack.shapes.php

我理解形状的概念,它对我来说似乎真的很有用,但我不明白为什么这个代码不会抛出任何错误:

<?hh

type Point2D = shape('x' => int, 'y' => int);

function dotProduct(Point2D $a, Point2D $b): int {
    return $a['x'] * $b['x'] + $a['y'] * $b['y'];
}

function main_sse(): void {
    echo dotProduct(shape('x' => 3, 'y' => 'this should cause an fatal error?'), shape('x' => 4, 'y' => 4));
}

main_sse();

'y' 键被定义为整数,但是当我传递一个字符串时,没有显示错误。谢谢你的帮助 :)

4

2 回答 2

13

实际上执行 Hack 代码并不一定要对所有内容进行类型检查。您需要实际运行一个单独的工具来强制执行类型系统,如此处链接的文档文章中所述。当你这样做时,你会得到一个看起来像这样的错误,这取决于你拥有的 HHVM 的确切版本:

File "shapes.php", line 10, characters 19-23:
Invalid argument (Typing[4110])
File "shapes.php", line 3, characters 41-43:
This is an int
File "shapes.php", line 10, characters 42-76:
It is incompatible with a string

如果您不运行类型检查器,现代版本的 HHVM 也会对您大喊大叫。我怀疑您正在运行旧版本,在我们意识到这是一个混乱点之前 - 抱歉!

当您运行类型不正确的代码时实际发生的是未定义的行为。Ed Cottrell 的回答对于当前版本的 HHVM 是正确的——我们做的事情与 PHP 强制类型相同——但请记住,这是未定义的行为,可能会在未来版本中更改,恕不另行通知。

于 2014-09-18T16:35:32.890 回答
3

解释器将尝试将'y'密钥评估为数字以进行计算。

例子:

echo 4 * '6';
// prints 24

echo 4 * '6foo';
// prints 24

echo 'foo' * 42;
// prints 0, because floatval('foo') === 0

你的情况就像第三个例子。 floatval('this should cause an fatal error?') === 0,所以计算为:

$a['x'] * $b['x'] + $a['y'] * $b['y'] === 3 * 4 + 0 * 4 === 12
于 2014-09-18T14:50:21.790 回答