On Fri, Feb 28, 2025, at 4:52 PM, Alwin Garside wrote: > Hello, > > Long time listener, first time caller here. > > Last week I had a shower thought about how it would be neat if we could > declare array shapes in PHP, and use them to provide structural > interfaces for arrays. > > After all, arrays are one of PHPs strongest features, and anyone who > has ever tried to use arrays/maps in other languages after getting used > to the versatility of PHP arrays will have to admit that nothing comes > close to their flexibility and ease of use. > > However, ironically, most of my friends, colleagues and fellow PHP devs > usually tend to shun PHP arrays, which has led to the widespread use of > Collection classes and the like. The usual argument is that arrays > don’t provide any way to declare their structure, and thus don’t > provide the ergonomics of autocompletion (even if you declare the array > shapes with docblock annotations IDE support is iffy at best) and don’t > provide any form of runtime type checking.
Your friends are correct. Arrays in PHP are an awful thing. They are twice as memory hungry as objects, they provide no static guarantees, and they're a security hole waiting to happen (and has in fact happened). And since PHP 8.0, *we have something equivalent to array shapes already that is vastly more efficient*: Constructor promotion. // This tells me nothing. $arrayPoint = ['x' => 1, 'y' => 2]; // This tells me everything. class Point { public function __construct( public int $x, public int $y, ) {} } $objectPoint = new Point(x: 1, y: 2); $objectPoint will use half as much memory as $arrayPoint. (Not meaningful in something this small, but if you have 100 of them...) It provides all the static type validation you can get in PHP right now. It's self-documenting. It works with everything else in the language. And it's already been available for 5 years. And now you can also toss readonly, private(set), or hooks around on it if you feel like it. This is a solved problem, and the solution is objects. Using arrays as pseudo-objects is the wrong approach 99.9% of the time. Collections are a different matter, as those are real lists. For more details: https://www.youtube.com/watch?v=nNtulOOZ0GY All that said! A side effect of the pattern matching RFC (which we'll be formally proposing real-soon-now-I-swear) is that it effectively gives an array-shape validation check for free. https://wiki.php.net/rfc/pattern-matching So yeah, no thank you on a separate array shapes RFC. --Larry Garfield