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

查看:25
本文介绍了在 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天全站免登陆