Re: Is there any interest for object constructor shorthand *just for stdClass*
| From: | Björn Larsson | Date: | Wed, 21 Oct 2020 09:38:53 +0000 |
| Subject: | Re: Is there any interest for object constructor shorthand *just for stdClass* | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-112086@lists.php.net to get a copy of this message | ||
Den 2020-10-21 kl. 01:30, skrev Larry Garfield:
On Tue, Oct 20, 2020, at 5:53 PM, tyson andre wrote:Well, but for us with a legacy code base where this is heavily used it would definitely be an improvement! It would enable a so called stepwise refinement :-) One typical usecase we have is populating an object with the result from a DB query or using an object to write to a DB. I'm also wondering how prevalent this feature is used in different Open Source libraries. r//Björn LarssonHi internals, e.g.The only data structure worse than an associative array -- from the point of view of performance, self-documentation, or usability -- is stdClass. :-) I can't recall using it in the last decade at least, and my code has been better for it. Especially now with constructor promotion and named properties, I'd prefer to just forget that stdClass exists and encourage others to do so as well. --Larry Garfield$x = object{key: object{'escaped-literal': $v2 }};(equivalent to$x = (object)['key' => (object)['escaped-literal' => $v2]];) For example, in JS, non-string key literals are surrounded in[]to unambiguously reference them. Here, that could beobject{[$key]: $value, [MY_CONST]: $other}- but(MY_CONST)would also work - https://externals.io/message/52990 was mentioned 9 years ago but would potentially conflict with future block expression RFCs -object{key: $value}is suggested here for similarity to named arguments Benefits: - Shorter and more readable code - casting an array to an object is an unintuitive and potentially hard to remember way to create an object literal - Make it easier for users to use objects for generic associative data instead of using arrays both for lists and associative data, in situations where it may result in more usable APIs For example,$x = new stdClass{}; $x->prop = new stdClass{}; $x->prop->a = $a; $x->prop->b = $b; // Could be shortened to $x = object{prop: object{a: $a, b: $b}} // $x = (object)['prop' => (object)['a' => $a, 'b' => $b]]This proposal is only for stdClass - there was not much interest in https://wiki.php.net/rfc/compact-object-property-assignment and the combination of named properties and constructor property promotion helps with the readability of other classes. Thanks, - Tyson