且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP 7中全局启用'strict_types'

更新时间:2023-12-05 23:42:40

这是故意不可能的,因为在对标量类型提示进行了长时间讨论之后采​​用的实现是这样的: https://wiki.php.net/rfc/scalar_type_hints_v5

This is deliberately not possible, because the implementation adopted after an extremely long discussion of scalar type hints was this one: https://wiki.php.net/rfc/scalar_type_hints_v5

它显式地给出了选择如何对任何函数的调用者(而不是其作者)检查标量类型的选择,以便:

It explicitly gives the choice of how scalar types are checked to the caller of any function, not its author, so that:

  • 如果您编写的具有标量类型提示的库,则即使没有以严格模式编写的代码(而是强制使用类型的代码)调用了函数,也可以保证函数具有请求的参数类型
  • 如果您编写一个库并希望使用传统的弱类型输入,您仍然可以使用带有类型提示的库(因为它们不会强迫您执行严格的类型检查)
  • 相反,如果您编写一个库并希望对调用的函数进行严格键入 ,则不必要求库的用户也启用严格键入
  • 内置函数的功能与用户定义的功能相同,并且默认情况下,现有代码运行的方式相同
  • 如果您启用严格输入,则需要更改代码以正确处理它
  • if you write a library with scalar type hints, your functions are guaranteed the parameter types requested, even if called by code not written in strict mode (the types are coerced instead)
  • if you write a library and want traditional weak typing, you can still make use of libraries that use type hints (because they don't force you to perform strict type checking)
  • contrarily, if you write a library and want strict typing for functions that you call, you don't have to require that users of your library also enable strict typing
  • built-in functions work the same way as user-defined ones, and existing code runs the same by default
  • if you turn on strict typing, you need to change your code to handle it correctly anyway

因此,由您决定告诉PHP哪些文件已编写为使用严格类型模式,哪些文件没有使用严格类型模式.而执行此操作的方法是使用declare语句.

It's therefore up to you to tell PHP which files have been written to use strict type mode, and which haven't; and the way to do this is using the declare statement.