Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

apache - Enabling 'strict_types' globally in PHP 7

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
// ...

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...