Casting array to any class

From: Date: Sat, 15 Oct 2022 11:13:19 +0000
Subject: Casting array to any class
References: 1 2 3 4 5 6 7 8 9  Groups: php.internals 
Request: Send a blank email to internals+get-118820@lists.php.net to get a copy of this message
Hi, in my every day experience, using custom DTO classes and different API, I often write code to instantiate my objects from associative arrays. What are your thoughts on introduce the (AnyType) cast to instantiate objects from associative array (or object properties also)? In my proposal, if AnyType implements __set_state(), casting should be syntactic sugar for:
    AnyType::_set_state((array) $data)
just for (useless) example, consider DateTime or DateTimeImmutable (both have __set_state() implementation); when applied to objects of that type, we can write:
    $dt = new DateTime();
    $dtArray = (array) $dt; // 3 elements array
    $copyOfDt = (DateTime) $dtArray; // or simply $copyOfDt = (DateTime) $dt;
In case AnyType does not implements __set_state(), casting should create a new instance, assigning values to properties, taken from array values with corresponding key (in a similar way class objects are created when row is fetched from database specifying PDO_FETCH_CLASS) eventually invoking __set() magic method for properties not declared; In this scenario,
    (object) ['one' => 1, 'two' => 2]
and
    (StdClass) ['one' => 1, 'two' => 2]
do exactly the same work. Reasons: - clear code - array to object conversion (casting) would be the simmetrical counterpart of object to array conversion Thanks, Gianni

« previous php.internals (#118820) next »