Re: RFC Proposal: Readonly Structs in PHP

From: Date: Fri, 08 Sep 2023 20:27:10 +0000
Subject: Re: RFC Proposal: Readonly Structs in PHP
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-121021@lists.php.net to get a copy of this message
Hi internals! I think it can be useful for structured data obtained from decoding JSONs or from a relational database. However, maybe there is an even better idea, which combines the best of two worlds: the world of your structs RFC, and native PHP arrays - something like "array shapes". For instance, taking the syntax from your proposed RFC (but perhaps the keyword changed to shape, or perhaps array class to reuse keywords - let's not bikeshed here) to define a shape, and adding a function like array_shape_coerce($array, $shapeType) which internally marks an array to be of a defined shape if it matches its definition (throws an exception otherwise, or perhaps returns true/false value or an enum for success/failure) and allows it to be passed where a certain shape type is expected. I think this could be a better approach than pure structs because it leaves all array-based PHP machinery available to such "structs", like array_map(), array_filter() etc. There is an open question of whether array coerced to shapes can be modified, and if yes, how to react to modifications. Perhaps the easiest solution is to have another function along the lines array_shape_seal($array, $shapeType) which not only marks array to be of shape (if the given array matches given shape), but also permits only such modifications which keep the array to be of this shape. And if the regular array_shape_coerce is used, then any modifications are permitted, but the array "loses" its shape. Regards, Illia / someniatko

« previous php.internals (#121021) next »