What do strict types do in PHP?

后端 未结 3 620

I\'ve seen the following new line in PHP 7, 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

3条回答
  •  隐瞒了意图╮
    2020-11-29 19:44

    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 an int would pass the type hint, including:

    • an int proper (242),
    • a float (10.17),
    • a bool (true),
    • null, or
    • a string with leading digits ("13 Ghosts").

    By setting strict_types=1, you tell the engine that int $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:

    Notice: A non well formed numeric value encountered in /Users/bishop/tmp/pmkr-994/junk.php on line 4
    100
    

    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:

    Fatal error: Uncaught TypeError: Return value of get_quantity() must be of the type int, string returned in example.php:4
    

    I think there's two lessons here, if you use type hints:

    • Use strict_types=1, always.
    • Convert notices to exceptions, in case you forget to add the strict_types pragma.

提交回复
热议问题