【PHP】PHP的类型声明是弱类型的

型宣言是什么?

在像给函数传递参数这样的情况下,可以对参数的类型进行限制,如下例所示。
如果传递了错误类型的参数,会发生致命错误。

<?php
function includeTax(int $price, bool $take_out = true) {
    if ($take_out) {
        return $price * 1.08;
    } else {
        return $price * 1.1;
    }
}

includeTax(100, false); // 100
includeTax('税抜100円', false); // Fatal error: Uncaught TypeError: Argument 1 passed to includeTax() must be of the type int, string given

上述的函数inculdeTax的参数$price被指定为int型,因此成功传递了正确类型的100,但是当传递了一个string类型的去税100日元时,会发生错误。

スクリーンショット 2020-01-01 20.59.55.png

引用PHP手册>语言参考>函数>类型声明

PHP的类型声明不是严格的。

然而,在声明标量类型1时存在陷阱。
标量类型的声明是弱类型的,所以如果传递了不匹配的参数类型,将会进行隐式类型转换以使其匹配。

具体来说,以下是例子之一。

<?php
function includeTax(int $price, bool $take_out = true) {
    // $priceは(int)100に変換される。
    if ($take_out) {
        return $price * 1.08;
    } else {
        return $price * 1.1;
    }
}

// string型で渡す。
includeTax('100', false); // 100
// float型で渡す。
includeTax(100.5, false); // 100

因为两种形式都可以转换为int类型,所以当传递给函数时会自动转换为int类型进行处理。特别是当以后者的float形式传递时,开发者可能期望返回110.55,但可能会困惑地得到不同的结果。

この挙動は、返り値の型宣言やプロパティ型指定2でも同様です。

要想禁用弱类型检查,可以使用下面的代码:

如果希望严格的类型检查,可以在文件开头使用declare(strict_types = 1)进行声明。

<?php
declare(strict_types = 1);

function includeTax(int $price, bool $take_out = true) {
    if ($take_out) {
        return $price * 1.08;
    } else {
        return $price * 1.1;
    }
}

includeTax('100', false); // Uncaught TypeError: Argument 1 passed to includeTax() must be of the type int, string given
includeTax(100.5, false); // Uncaught TypeError: Argument 1 passed to includeTax() must be of the type int, string given

然而,这种严格的类型化并不适用于整体。需要为每个想要严格类型化的单独文件进行声明。

引用文献

PHP手册
PHP初学者入门
【决定开展!】何为在PHP7中实施的标量类型声明?

布尔值 (boolean) 整数 (integer) 浮点数 (float, double) 字符串 (string) 是四种类型。

属性类型标注是从7.4版本开始的新功能。

bannerAds