On Sat, Sep 25, 2021 at 10:45 AM tyson andre <tysonandre...@hotmail.com> wrote:
> In PHP 8.1, it is possible to allow constructing any class name in an > initializer, after the approval of > https://wiki.php.net/rfc/new_in_initializers > > ``` > php > static $x1 = new ArrayObject(['key' => 'value']); > php > static $x2 = new stdClass(); > php > static $x3 = (object)['key' => 'value']; > > Fatal error: Constant expression contains invalid operations in php shell > code on line 1 > ``` > > What are your thoughts on allowing the `(object)` cast in initializer > types where `new` was already allowed, but only when followed by an array > literal node. > > I think for consistency's sake, we'd want to provide a base constructor to stdClass to take an associative array that maps into dynamic properties, e.g. class stdClass { public function __construct(array $props) { foreach ($prop as $name => $val) { $this->$name = $val; } } } Then you could: php> static $x3 = new stdClass(['key' => 'value']); This avoids special-casing object cases in the engine while making it clear that a stdClass is what you wind up with, and honestly I think it'd be a useful pattern to use when initializing stdClass with defaults elsewhere. As to whether or not we SHOULD: While using declared props is preferred in the vast majority of cases, both for performance and for readability, there are legitimate cases where a short lived container wants the flexibility and convenience of an untyped, dynamic structure like an associative array with the visually clean aesthetic of object access. stdClass does that, and even if deprecation of dynamic properties passes it will continue to do that. I started this paragraph ambivalent about the feature, but I think I convinced myself around to a +1, though in the constructor form, not the cast form. -Sara