logoalt Hacker News

Tadpole9181 • today at 3:59 PM • 0 replies • view on HN

If I could take a tangent and talk about the infuriating implicit-casting behavior of arrays in PHP?

  declare(strict_types=1);
  
  /\* @var array<string, int> \*/
  function foo(string $key) {
      echo $key;
  }
  
  $foo = [
      'a' => 10,
      '1' => 15,
  ];
  
  foreach ($foo as $key => $_) {
      foo($key);
  }
The static analyzer will say this is safe (sans a bleeding edge setting in PHPStan), but it will throw a type error when it runs. Because the string '1' is, despite having strict types enabled, still implicitly cast to the number 1.