On 23/10/2020 16:08, Andreas Bittner wrote:
Closing I would like to make a short point with regards to the `(object)` cast: Both a cast of \stdClass to `(array)` and a cast of arrays to `(object)` are common use cases in (JSON-)API development. It is not unheard of for API signatures to contain certain properties of the JSON response object only if some conditions are met. Currently the best way to achieve this is either by dynamically adding properties to an existing \stdClass object, or by populating an array and `(object)` casting it later.


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?


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;
}


The only difference I'm aware of is that you can no longer use "stdClass" as a type constraint, but I'm not sure what value that would ever have. Indeed, with anonymous classes you could trivially add a much more meaningful type constraint using an empty interface:

instead of:

function getFromDB(...): stdClass {
      $result = new stdClass;
      foreach ( $this->blah()  as $column => $value ) {
            $result->{ $column } = $value;
      }
      return $result;
}


you can write:

interface DynamicDBItem {}

function getFromDB(...): DynamicDBItem {
      $result = new class implements DynamicDBItem {};
      foreach ( $this->blah()  as $column => $value ) {
            $result->{ $column } = $value;
      }
      return $result;
}


Regards,

--
Rowan Tommins (né Collins)
[IMSoP]

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

Reply via email to