> On Oct 23, 2020, at 2:33 PM, Rowan Tommins <rowan.coll...@gmail.com> wrote: > > 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. > On Oct 23, 2020, at 11:08 AM, Andreas Bittner <p...@philiagus.de> wrote: > > 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 -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php