PHP 7:使用严格和非严格类型提示?

时间:2015-12-08 21:05:13

标签: php-7

因此,PHP 7现在具有标量类型提示(w00t!),并且您可以根据PHP中的设置使用类型提示严格或非严格。 Laracasts使用define,IIRC设置了这个。

有没有办法在一个文件(如数学库)中对标量进行严格的类型提示,同时在其他地方使用非严格,而不是随意更改代码中的设置?

我希望避免因为不喜欢语言设置而引入错误,但我喜欢这个想法。

1 个答案:

答案 0 :(得分:4)

事实上,你可以混合搭配你心中的内容,事实上这个功能是专门为这种方式设计的。

declare(strict_types=1);不是语言设置或配置选项,它是一个特殊的每文件声明,有点像namespace ...;。它仅适用于您使用它的文件,不会影响其他文件。

所以,例如:

<?php // math.php

declare(strict_types=1); // strict typing

function add(float $a, float $b): float {
    return $a + $b;
}

// this file uses strict typing, so this won't work:
add("1", "2");
<?php // some_other_file.php

// note the absence of a strict typing declaration

require_once "math.php";

// this file uses weak typing, so this _does_ work:
add("1", "2");

返回键入的工作方式相同。 declare(strict_types=1);适用于文件中的函数调用(NOT声明)和return语句。如果您没有declare(strict_types=1);语句,则该文件使用“弱键入”模式。