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

Der*_*and 1 php-7

所以 PHP 7 现在有标量类型提示(w00t!),您可以根据 PHP 中的设置将类型提示设为严格或非严格。Laracasts 使用定义,IIRC 设置它。

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

我想通过不烦躁的语言设置来避免引入错误,但我喜欢这个想法。

And*_*rea 5

事实上,您可以根据自己的喜好进行混合搭配,事实上,该功能是专门为这种方式设计的。

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");
Run Code Online (Sandbox Code Playgroud)
<?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");
Run Code Online (Sandbox Code Playgroud)

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