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?
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:
int
parameter will convert '123'
to 123
, but error on 'hello'
)'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:
From the point of view of someone writing a reusable library:
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.
PHPStorm has an inspection to help you with this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With