Enabling 'strict_types' globally in PHP 7

PHPStorm has an inspection to help you with this:

enter image description here


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 introduces two modes for scalar type parameters, which both guarantee that the function receiving the parameters gets the types that it requires in its signature. However, it provides two modes for how calling code can achieve that:

  • in mode 0, it automatically validates and casts certain scalar types (e.g. int parameter will convert '123' to 123, but error on 'hello')
  • in mode 1, it requires the caller to do that validation and casting before-hand, and rejects any parameter not of the correct type (e.g. both '123' and 'hello' are rejected for an int parameter)

The choice of mode is per-file, and based on the caller of the function, because:

  • the setting needs to affect built-in functions as well as user-defined ones
  • all code that calls functions needs to be checked or updated to work correctly in mode 1, but most old code will run fine in mode 0
  • with a global setting, you could only use libraries which had been tested with both modes, or the same mode you prefer
  • files that don't declare their preferred mode need to continue to work similarly to PHP 5.x to allow existing code to run; that is only possible if the default is mode 0

From the point of view of someone writing a reusable library:

  • regardless of the setting, your functions are guaranteed to receive the parameter types requested
  • if you want to receive errors when you call functions with the wrong types, you can use mode 1 without forcing other applications and libraries to be on the same setting
  • if you want to have the automatic checks and casts of mode 0, you can do that, but still interact with other libraries and applications which run in mode 1
  • old libraries which were written before PHP 7.0 (or which needed to support both when it came out) will continue to work roughly as before, because the default mode 0 is similar to existing behaviour for built-in functions

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.


Essentially no.

Because if you only require libraries that used strict mode you will cause an unnecessary separation of packages. Also consider the strict/weak types option is just an extra in PHP.