I've seen this new line in PHP7 but nobody really explains what it means. I've googled it and all they talk about is will you be enabling it or not like a poll type of thing.
declare(strict_types = 1);
What does it do? How does it affect my code? Should I do it? Some explanation would be nice.
strict_types
affects type coercion.Using type hints without
strict_types
may lead to subtle bugs.Prior to strict types,
int $x
meant "$x
must have a value coercible to an int." Any value that could be coerced to anint
would pass the type hint, including:242
),10.17
),true
),null
, or"13 Ghosts"
).By setting
strict_types=1
, you tell the engine thatint $x
means "$x must only be an int proper, no type coercion allowed." You have great assurance you're getting exactly and only what was given, without any conversion and potential loss.Example:
Yields a potentially confusing result:
Most developers would expect, I think, an
int
hint to mean "only an int". But it doesn't, it means "anything like an int". Enabling strict_types gives the likely expected and desired behavior:Yields:
I think there's two lessons here, if you use type hints:
strict_types=1
, always.strict_types
pragma.From Treehouse blog :
By default, PHP will cast values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.
Strict types disabled ( eval ) :
It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration.
To enable strict mode, the declare statement is used with the strict_types declaration:
Strict types enabled ( eval ) :
working example :