# Is there any interest for object constructor shorthand *just for stdClass*

- Thread: https://staging.externals.io/message/112082
- Original archive: https://news-web.php.net/php.internals/112082
- Started by tyson andre on 2020-10-20T22:53:39+00:00
- Messages: 9
- RFC: Compact Object Property Assignment (Declined) — https://staging.externals.io/rfc/compact-object-property-assignment.md
- Reply by email to internals@lists.php.net
- More for agents: search with https://staging.externals.io/search.md?q={query} · RFCs at https://staging.externals.io/rfc.md · JSON API at https://staging.externals.io/api · documentation at https://staging.externals.io/llms.txt

---

## #112082 — tyson andre — 2020-10-20T22:53:39+00:00

URL: https://staging.externals.io/message/112082#112082

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

---

## #112084 — Larry Garfield — 2020-10-20T23:30:41+00:00

URL: https://staging.externals.io/message/112082#112084 · In reply to: #112082

> 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

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

---

## #112104 — Hans Henrik Bergan — 2020-10-22T18:40:04+00:00

URL: https://staging.externals.io/message/112082#112104

@Rowan Tommins

not saying this is a good idea or anything, but i just want to point
out that there's another way to do it in
7.4
$object = new class($foo, $foo * 2, $nextBaz) {
     public int $foo;
     public int $bar;
     public int $baz;
     public function __construct($foo, $bar, $baz) {
        for($i=0;$i<func_num_args();++$i){
            $name = ((new
ReflectionParameter([$this,__FUNCTION__],$i))->getName());
            $this->$name = $$name;
        }
     }
};

haha finally found a use-case for variable-variables


>
> Den 2020-10-21 kl. 22:45, skrev Rowan Tommins:
>
> > […]
> We considered arrays once when migrating our PHP 5 codebase to PHP 7, but
> the cost benefit analyse didn't show any worth while business aspects. The
> only thing we needed to do was to add one line with new stdClass for the
> PHP 7 migration to succeed.
> > […]
>
>
> True, we looked into anonymous classes as another option but it didn't
> improve readability, rather the opposite.
>
> > […]
>
> That's a very good point! We have code today that uses stdClass, so it
> would probably only come into play for new code since the existing
> code runs perfectly fine :-)
> > […]
> Interesting alternatives!
> > […]
> r//Björn L
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php

---

## #112105 — Andreas Bittner — 2020-10-23T15:08:05+00:00

URL: https://staging.externals.io/message/112082#112105 · In reply to: #112082

> 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]]
> ```

Creating a new syntax, that is only used in context of \stdClass, feels 
like overkill. Unfortunately, I cannot come up with a use case for this 
syntax, outside of the \stdClass context.

I would also debate the point of the new syntax being more readable 
compared to the `(object)` cast, but that very much depends on what the 
reader is used to. I would however like to point out that shorter isn't 
always better and sometimes more verbose code is easier to understand. 
Imho a language shouldn't look like code-golf by recommendation. But I 
don't want to and hope I didn't sidetrack the discussion.

With regards to the matter at hand I can see where you are coming from. 
`(object)['prop' => 1, ...]` feels very indirect, needlessly creating an 
array instance just to get an object out of it.

Wouldn't it be opportune to just use named arguments?

```
$x = new \stdClass(
     prop: new \stdClass(
         a: $a,
         b: $b
     )
);
```

While this isn't as short as the object{} suggestion, it doesn't add any 
additional language constructs. The signature of \stdClass constructor 
would change to `\stdClass(...$defaultProperties)`. Maybe this is the 
kickoff for variadic property promotion `__constructor(public mixed 
...$properties)`.

The following would be true:
`new \stdClass(1, 2, 3, prop: 1.2) == (object)[1, 2, 3, 'prop' => 1.2];`

On the subject of dynamic/variable property names: I would suggest that 
a RFC for the syntax `functionA($parameterName: 'value')` should be 
submitted at some point. This would replace the already working 
`functionA(...[$parameterName => 'value'])`. Maybe we even find a way of 
using constants as well, which would could be something like your 
suggested `functionA([SOME_CONST]: 'value')`.
This would allow everyone to benefit from the change, not only \stdClass.

Closing I would like to make a short point with regards to the 
`(object)` cast:
Both a cast of \stdClass to `(array)` and a cast of arrays to `(object)` 
are common use cases in (JSON-)API development. It is not unheard of for 
API signatures to contain certain properties of the JSON response object 
only if some conditions are met. Currently the best way to achieve this 
is either by dynamically adding properties to an existing \stdClass 
object, or by populating an array and `(object)` casting it later.

- Andreas

---

## #112110 — Rowan Tommins — 2020-10-23T18:33:10+00:00

URL: https://staging.externals.io/message/112082#112110

> Closing I would like to make a short point with regards to the 
> `(object)` cast:
> Both a cast of \stdClass to `(array)` and a cast of arrays to 
> `(object)` are common use cases in (JSON-)API development. It is not 
> unheard of for API signatures to contain certain properties of the 
> JSON response object only if some conditions are met. Currently the 
> best way to achieve this is either by dynamically adding properties to 
> an existing \stdClass object, or by populating an array and `(object)` 
> casting it later. 


I don't follow; is the resulting JSON different if you cast to object, 
or is there some other reason you prefer an object over using an 
associative array directly?


Also, to clarify my earlier comment about stdClass not being necessary 
now we have anonymous classes, I meant it very directly: every time you 
write "new stdClass" you can write "new class {}" instead.

The fact that "(object)$foo" creates an instance of "stdClass" rather 
than an instance of "class{}" is just a historical wart, which can be 
easily replaced:

function array_to_object($arr): object {
     $obj = new class {};
     foreach ( $arr as $key => $value ) {
         $obj->{$key} = $value;
     }
     return $obj;
}


The only difference I'm aware of is that you can no longer use 
"stdClass" as a type constraint, but I'm not sure what value that would 
ever have. Indeed, with anonymous classes you could trivially add a much 
more meaningful type constraint using an empty interface:

instead of:

function getFromDB(...): stdClass {
       $result = new stdClass;
       foreach ( $this->blah()  as $column => $value ) {
             $result->{ $column } = $value;
       }
       return $result;
}


you can write:

interface DynamicDBItem {}

function getFromDB(...): DynamicDBItem {
       $result = new class implements DynamicDBItem {};
       foreach ( $this->blah()  as $column => $value ) {
             $result->{ $column } = $value;
       }
       return $result;
}


Regards,

-- 
Rowan Tommins (né Collins)
[IMSoP]

---

## #112111 — Mike Schinkel — 2020-10-23T20:14:49+00:00

URL: https://staging.externals.io/message/112082#112111 · In reply to: #112110

> 
> 
> I don't follow; is the resulting JSON different if you cast to object, or is there some other reason you prefer an object over using an associative array directly?

The by-reference semantics of objects vs arrays in PHP.

> Also, to clarify my earlier comment about stdClass not being necessary now we have anonymous classes, I meant it very directly: every time you write "new stdClass" you can write "new class {}" instead.
> 
> The fact that "(object)$foo" creates an instance of "stdClass" rather than an instance of "class{}" is just a historical wart, which can be easily replaced:
> 
> function array_to_object($arr): object {
>     $obj = new class {};
>     foreach ( $arr as $key => $value ) {
>         $obj->{$key} = $value;
>     }
>     return $obj;
> }

That pattern can have a non-insignificant performance penalty when dealing with a large number of objects, a use-case that is not infrequent when processing JSON, especially responses returned via an HTTP API.


> 
> 
> Wouldn't it be opportune to just use named arguments?
> 
> $x = new \stdClass(
>    prop: new \stdClass(
>        a: $a,
>        b: $b
>    )
> );

You illustrate of useful pattern here. 

What would be nicer, however, would be an object instantiation shorthand that would omit the "new" by using braces:

$x = \stdClass{
   prop: \stdClass{
       a: $a,
       b: $b,
   },
}

Also:

$x = \Foo{
   prop: \Bar{
       a: $a,
       b: $b,
   },
}

And for instantiating anonymous classes:

$x = {
   prop: {
       a: $a,
       b: $b,
   },
}


-Mike

---

## #112112 — Rowan Tommins — 2020-10-23T20:53:23+00:00

URL: https://staging.externals.io/message/112082#112112 · In reply to: #112111

> > […]
>wrote:
> > […]
>object, or is there some other reason you prefer an object over using
>an associative array directly?
>
>The by-reference semantics of objects vs arrays in PHP.


*shrug* If you want things to be mutable between functions, stick an & in front of them; if you want copy-on-write performance, leave it to the engine. That doesn't seem to have anything to do with JSON or API as a use case.



>That pattern can have a non-insignificant performance penalty when
>dealing with a large number of objects, a use-case that is not
>infrequent when processing JSON, especially responses returned via an
>HTTP API.


That gives us all the more reason to look for efficient ways of populating anonymous class instances, then. (And, indeed, populating actual named classes, if such a penalty applies to them too.)

My point was that if we didn't already have it, making (object)$array create an instance of an anonymous class would feel natural and not lose anything that we have now.

I see stdClass as a badly named and no longer necessary kludge, and would rather see features that help replace it than features that rely on it.

Regards,

-- 
Rowan Tommins
[IMSoP]

---

## #112114 — Andreas Bittner — 2020-10-26T09:02:52+00:00

URL: https://staging.externals.io/message/112082#112114 · In reply to: #112112

> > […]
> 
> 
> *shrug* If you want things to be mutable between functions, stick an & in front of them; if you want copy-on-write performance, leave it to the engine. That doesn't seem to have anything to do with JSON or API as a use case.

Agreed. My original point might have been badly phrased and was only made to reinforce that 
\stdClass is currently needed and widely used as no other structure exists that offers dynamic 
property names while still being forcefully JSON encoded as a JSON object.
We could replace this with another class. Maybe a real map implementation. But without the 
replacement being present \stdClass should be removed.

With regards to the JSON looking different when casting to object:

```
json_encode([1,2,3]); // result: [1,2,3]
json_encode((object)[1,2,3]); // result: {"0":1,"1":2,"2":3}

json_encode([]); // result: []
json_encode((object)[]); // result: {}

json_encode(['key' => 'value']); // result: {"key":"value"}
json_encode((object)['key' => 'value']); // result: {"key":"value"}
```

While it only applies to empty and sequential arrays I think it best to hand the desired structure 
(object or array) from PHP to json_encode and not leave it to interpretation. I usually provide 
json_encode with an object where I want to have an object result, even if I know that the source is 
already an array with string keys.

> > […]
> 
> 
> That gives us all the more reason to look for efficient ways of populating anonymous class instances, then. (And, indeed, populating actual named classes, if such a penalty applies to them too.)

I am not familiar with internals, but I can't imagine that omitting `new` could have any performance 
impact at all, as long as the constructor would still be called for non \stdClass objects.

For \stdClass objects it might be possible to find a performant way of handling `new \stdClass(...)` 
with close to (if not the same) performance as a proposed `{prop: 'value'}`.

I'm not clear on the advantages of the new syntax from a language perspective.

Would `\Bar{a: $a, b: $b}` still call the constructor?
If yes, it would be a cosmetic change only with negligible (if any) performance impact compared to 
`new \Bar` with named parameters.
If no and the arguments would be written directly to the public properties of the object, I would 
consider it a bad pattern, given that internals about the setup of the valid object might be unclear 
to the outside user. What if the class has additional private properties? The control over valid 
construction of an object must be located in the class defining the object imho.

> I see stdClass as a badly named and no longer necessary kludge, and would rather see features that help replace it than features that rely on it.

Do we already have a comprehensive list of features and use cases for \stdClass? If not I would 
offer to compile one to the best of my knowledge for a separate discussion on how to replace 
\stdClass if possible and needed.

---

## #112123 — Rowan Tommins — 2020-10-26T14:24:48+00:00

URL: https://staging.externals.io/message/112082#112123

> With regards to the JSON looking different when casting to object:
>
> ```
> json_encode([1,2,3]); // result: [1,2,3]
> json_encode((object)[1,2,3]); // result: {"0":1,"1":2,"2":3}
>
> json_encode([]); // result: []
> json_encode((object)[]); // result: {} 


Thanks, I hadn't thought of that. For cases as trivial as that, we have 
JSON_FORCE_OBJECT, but that's no use for creating structures like [{}, {}]


> \stdClass is currently needed and widely used as no other structure 
> exists that offers dynamic property names while still being forcefully 
> JSON encoded as a JSON object.
> We could replace this with another class. Maybe a real map 
> implementation. But without the replacement being present \stdClass 
> should be removed.


Just to be clear, *any* object (except for a few with magic behaviour) 
can have dynamic property names added. As far as I know, defining "class 
stdClass {}" would be completely equivalent to what stdClass currently 
does (i.e. nothing).

The only thing that makes stdClass at all special is the built-in 
functionality that returns it, notably the "object cast" short-hand for 
creating an instance and dynamically setting properties on it. The 
*functionality* (if not necessarily the *performance*) of that 
short-hand can definitely be replicated with any normal or anonymous 
class: https://3v4l.org/fGRBj



> Do we already have a comprehensive list of features and use cases for 
> \stdClass? If not I would offer to compile one to the best of my 
> knowledge for a separate discussion on how to replace \stdClass if 
> possible and needed.


I guess you could search the manual for built-in functions and operators 
that return stdClass instances. I doubt there are any that explicitly 
require them as input.

For userland code, I'm not aware of any scenario where "new stdClass" 
could not be replaced by "new class {}", or why a polyfill would be any 
more than "if ( ! class_exists('stdClass') ) { class stdClass{} )".


Regards,

-- 
Rowan Tommins (né Collins)
[IMSoP]
