logoalt Hacker News

hparadiz • today at 11:55 AM • 2 replies • view on HN

With how good PHPDoc and Phan are these days I don't really think about it anymore. You can sort of have typed array by implementing Iterator, Countable, ArrayAccess, and optionally Indexing but I assume you mean defining types of array values.


Replies

Tadpole9181 • today at 3:59 PM

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.
someothherguyy • today at 3:53 PM

pretty naive take, no run time guarantees, basically swinging on hope to keep your shit together. phpstan drops types on static analysis for deeply nested arrays/objects for example. or even those with many members.