Is there any interest for object constructor shorthand *just for stdClass*
| From: | tyson andre | Date: | Tue, 20 Oct 2020 22:53:39 +0000 |
| Subject: | Is there any interest for object constructor shorthand *just for stdClass* | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-112082@lists.php.net to get a copy of this message | ||
Hi internals,
e.g.
$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 be object{[$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