ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
整个文档中都会看到类型推断的效果,并且在后面也是非常重要的部分。一个例子可以展示类型推断: > The effects of type inference have been seen throughout this document and will continue to be important. A simple example shows type inference at work: ~~~ class Main { public static function main() { var x = null; $type(x); // Unknown<0> x = "foo"; $type(x); // String } } ~~~ 特殊的构造 $type 前面有提到过,在简单的介绍函数类型(第2.6节)的部分,现在正式介绍它: > The special construct $type was previously mentioned in order to simplify the explanation of the Function Type (Section 2.6) type, so let us now introduce it officially: **$type** >[warning] 构造:$type $type 是一个编译时机制,可以像函数一样调用,接受一个单独的参数。编译器执行参数表达式并输出表达式的类型。 >[warning] Construct: $type $type is a compile-time mechanism being called like a function,with a single argument. The compiler evaluates the argument expression and then outputs the type of that expression. 在上面的例子中,第一个 $type 输出 Unknow<0> 。这是一个 单形(第2.9节),一个还不知道的类型。下一行 x="foo" 赋值一个字符串字面量到 x ,使得 单形合一(第3.5节)为 String 。我们然后可以看到x的类型实际上被改变为 String 。 > In the example above,the first $type prints Unknown<0>. This is a monomorph(2.9),a type that is not yet known. The next line x = "foo" assigns a String literal to x, which causes the unification (3.5) of the monomorph with String. We then see that the type of x indeed has changed to String. 每当一个不同于 Dynamic(第2.7节)的类型被使用一个单形统一时,那个单形则变为该类型:它改变为那个类型。因此它之后就不能变形为一个不同的类型,一个属性在它的名字的mono部分表示。 > Whenever a type other than Dynamic(Section2.7) is unified with a monomorph,that monomorph becomes that type: it morphs into that type. Therefore it cannot morph into a different type afterwards, a property expressed in the mono part of its name. 遵循合一的规则,类型推断可以在复合类型中出现: > Following the rules of unification, type inference can occur in compound types: ~~~ class Main { public static function main() { var x = []; $type(x); // Array<Unknown<0>> x.push("foo"); $type(x); // Array<String> } } ~~~ 变量 x 是首先初始化为一个空的数组。此时我们可以看出x的类型是一个数组,但是我们还不知道数组元素的类型。必然,x的类型是 Array<Unknow<0>>。只有在推送一个字符串到数组后我们才知道类型变为 Array<String>。 > Variable x is first initialized to an empty Array. At this point we can tell that the type of x is an array, but we do not yet know the type of the array elements. Consequentially, the type of x is Array<Unknown<0>>. It is only after pushing a String onto the array that we know the type to be Array<String>.