PHP7 strict mode, globally?

Does anyone know, if instead of having to write

declare(strict_types=1);

at the top of every PHP file, it can simply be set globally? I don’t think it is possible. Would it make any sense to have that capability?

Scott

Essentially, no. The problem is, if a third party library was relying on weak-mode and you enforced strict mode globally, that library would cease to work. You’d need to only use libraries that used strict mode causing an unnecessary segregation of packages.

It’s important to remember that declaring strict mode affects function calls in the file, not function definitions so if one file had:

declare(strict_types=1);
function foo(int $x) {
}

You could still call it from another file with weak types:

require_once 'foo.php';
foo('123');

Of course, if you declared strict types in the file you’re calling the method in:

declare(strict_types=1);
require_once 'foo.php';
foo('123');

This will now error.

The problem with a global strict types, is if you have a library that relies on weak types:

function foo(int $x) {
}

function bar() {
 foo('1234');
}

and works perfectly with them, globally enforcing strict types would make you unable to use the library in your project.

edit: That said, I don’t really like the way PHP has implemented this. I know they were trying to make everyone happy but having to consider the strict/weak types option is just an extra thing that we need to consider when developing, they should just have implemented one or the other imho.

I hope it will come down to something like HHVM and Hack at some point, where, if you want the JIT compiler goodness (assuming there will be one), then you are in strict mode globally.

Scott

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.