在PHP 7中全局启用'strict_types' [英] Enabling 'strict_types' globally in PHP 7

查看:693
本文介绍了在PHP 7中全局启用'strict_types'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将网站从PHP5迁移到PHP7,并且已经开始使用添加的严格键入功能.但是,这需要我以以下行开始所有文件:

I'm currently migrating my website from PHP5 to PHP7, and I've started using the strict typing feature that was added. However this requires me to begin all files with the following line:

<?php declare(strict_types=1);

// All other code here
// ...

所以我想知道,有没有办法使用php.ini或apache配置文件来全局启用strict_types,所以我不必每次都写此行,如果可以的话,如何启用此功能?

So I was wondering, is there any way to enable strict_types globally using something like php.ini or the apache configuration file so I don't have to write this line every time, and if so how could I enable this?

推荐答案

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

这篇关于在PHP 7中全局启用'strict_types'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆