Re: Casting array to any class

From: Date: Sat, 15 Oct 2022 14:22:13 +0000
Subject: Re: Casting array to any class
References: 1 2 3 4 5 6 7 8 9 10  Groups: php.internals 
Request: Send a blank email to internals+get-118824@lists.php.net to get a copy of this message
On Sat, 15 Oct 2022 at 13:14, Gianni Gentile <g.gentile@parentesigraffe.com> wrote: > > What are your thoughts on introduce the (AnyType) cast to > instantiate > objects from associative array (or object properties also)? It seems a pretty bad idea. In particular, it makes for hard to maintain code as it doesn't give a place for error checking to occur. Though I do actually use that pattern in code. Below is a trait that accomplishes it that should only be used in prototype code. Having it as a trait means at least I can debug through the initialization and see if it's missing properties from the array, But in general, you'd really need to make a strong argument for why it should be in core, not just why anyone would be against it. cheers Dan Ack trait FromArray { /** * @param array $data * @return static * @throws \ReflectionException */ public static function fromArray(array $data): self { $reflection = new \ReflectionClass(__CLASS__); $instance = $reflection->newInstanceWithoutConstructor(); foreach ($instance as $key => &$property) { $property = $data[$key]; } return $instance; } }

« previous php.internals (#118824) next »