问题描述
因此,PHP 7现在具有标量类型提示(w00t!),并且可以根据PHP中的设置使类型提示为严格或非严格.播客使用IIRC定义进行设置.
So PHP 7 has scalar type hinting now (w00t!), and you can have the type hints be strict or non-strict depending on a setting in PHP. Laracasts set this using define, IIRC.
有没有一种方法可以对一个文件(例如数学库)中的标量进行严格的类型提示,而同时在其他地方使用非严格的类型提示而不必随意更改代码中的设置?
Is there a way to have strict type hinting on scalars in one file (like a math library) while at the same time using non-strict elsewhere WITHOUT just arbitrarily changing settings in your code?
我想避免由于对语言设置不满意而引入错误,但是我喜欢这个主意.
I'd like to avoid introducing bugs by not fidgeting with the language settings, but I like this idea.
推荐答案
实际上,您可以混合并匹配您内心的内容,实际上,该功能是专门为这种方式设计的.
Indeed, you can mix and match to your heart's content, in fact the feature was specifically designed to work that way.
declare(strict_types=1);
不是语言设置或配置选项,它是每个文件的特殊声明,有点像namespace ...;
.它仅适用于您在其中使用的文件,不会影响其他文件.
declare(strict_types=1);
isn't a language setting or configuration option, it's a special per-file declaration, a bit like namespace ...;
. It only applies to the files you use it in, it won't affect other files.
例如,
<?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);
适用于文件中的函数 calls (不声明)和return
语句.如果没有declare(strict_types=1);
语句,则文件使用弱键入"模式.
Return typing works the same way. declare(strict_types=1);
applies to function calls (NOT declarations) and return
statements within a file. If you don't have a declare(strict_types=1);
statement, the file uses "weak typing" mode.
这篇关于PHP 7:同时使用严格和非严格类型提示吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!