Skip to content

Instantly share code, notes, and snippets.

@Trainmaster
Created January 11, 2018 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Trainmaster/1d29b9bc1774e6ec3e2eebbe602de176 to your computer and use it in GitHub Desktop.
Save Trainmaster/1d29b9bc1774e6ec3e2eebbe602de176 to your computer and use it in GitHub Desktop.
Behaviour of weak type check (string/float)
<?php
function add(float $a, float $b): float {
return $a + $b;
}
<?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
@Trainmaster
Copy link
Author

Trainmaster commented Jan 11, 2018

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment