On 22/06/2021 01:03, tyson andre wrote:
If linters and automatic fixers were set up for a project to enforce it (e.g. 
phpcbf),
there would only be one way that literals would be used in a project either way.


The only way to be consistent across a whole project would be to never use the new syntax, since it can't be used for all arrays/keys. Otherwise, you'd have to encourage either mixing the styles within one array, or switching arrays back and forth if keys are added and removed which meet/don't meet the requirements.


Also, with no common interface between those anonymous classes,
using just anonymous classes would be writing functions that accept any object 
or return any object,
which would be error prone and hard to analyze.

Those anonymous classes wouldn't have any ancestors in common for `instanceof` 
checks.


Yes, the simplest anonymous class, with only untyped public properties, is equivalent to stdClass, which in turn is equivalent to a plain array. However, you can then add natively checked types, implement interfaces, extend base classes, use traits, and so on. And then you can switch to a named class with minimal impact on surrounding code.

Unfortunately, a neat syntax like object(foo: $foo) loses most of those advantages; what we need is something that lets us keep the class body, but "capture" variables from the declaring scope somehow, e.g.

$foo = new class(public bool success: true, public array data: $data, public CursorInterface cursor: $cursor) implements Bar { use BarTrait; }

or

$foo = new class implements Bar { public bool $success = true; public array $data = lexical $data; public CursorInterface $cursor = lexical $cursor; use BarTrait; }



Also, if there were optional parameters, that can be represented in 
non-standard JSDoc supported by static analyzers
(`success: bool, data?: array, cursor?: CursorInterface, errorMessage?: 
string`),
but that wouldn't be represented in an anonymous class
(setting a property to null is not the same as omitting it).


Certainly, if what you have are dynamic keys rather than fixed properties, then a key-value array makes sense, and I'm not suggesting we remove that from the language. But I do think we should be adding richer choices beside arrays, rather than just more ways to write the same thing.

Regards,

--
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to