Created
January 11, 2018 10:12
-
-
Save Trainmaster/1d29b9bc1774e6ec3e2eebbe602de176 to your computer and use it in GitHub Desktop.
Behaviour of weak type check (string/float)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function add(float $a, float $b): float { | |
return $a + $b; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require "add.php"; | |
var_dump(add("1", "1")); | |
// float(2) | |
var_dump(add("1", "1foo")); | |
// PHP Notice: A non well formed numeric value encountered | |
// float(2) | |
var_dump((float) "foo"); | |
// float(0) | |
var_dump(floatval("foo")); | |
// float(0) | |
var_dump(add("1", "foo")); | |
// PHP Fatal error: Uncaught TypeError: Argument 2 passed to add() must be of the type float, string given |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The example was taken from https://wiki.php.net/rfc/scalar_type_hints_v5#example, modified and tested with
PHP 7.1.12-3+ubuntu16.04.1+deb.sury.org+1 (cli)
.