且构网

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

在 PHP 7 中全局启用“strict_types"

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

这是故意不可能的,因为在对标量类型提示进行了长时间讨论后采用的实现是这样的: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.