Reputation: 626
So PHP 7 has scalar type hinting now (w00t!), and you can have the type hints be strict or non-strict depending on a setting in PHP. Laracasts set this using define, IIRC.
Is there a way to have strict type hinting on scalars in one file (like a math library) while at the same time using non-strict elsewhere WITHOUT just arbitrarily changing settings in your code?
I'd like to avoid introducing bugs by not fidgeting with the language settings, but I like this idea.
Upvotes: 1
Views: 1303
Reputation: 19533
Indeed, you can mix and match to your heart's content, in fact the feature was specifically designed to work that way.
declare(strict_types=1);
isn't a language setting or configuration option, it's a special per-file declaration, a bit like namespace ...;
. It only applies to the files you use it in, it won't affect other files.
So, for example:
<?php // math.php
declare(strict_types=1); // strict typing
function add(float $a, float $b): float {
return $a + $b;
}
// this file uses strict typing, so this won't work:
add("1", "2");
<?php // some_other_file.php
// note the absence of a strict typing declaration
require_once "math.php";
// this file uses weak typing, so this _does_ work:
add("1", "2");
Return typing works the same way. declare(strict_types=1);
applies to function calls (NOT declarations) and return
statements within a file. If you don't have a declare(strict_types=1);
statement, the file uses "weak typing" mode.
Upvotes: 5