On 04/05/2019 15:58, Steven Wade wrote:
The idea is to add a new magic method "__toArray()" that would allow a 
developer to specifiy how a class is cast to an array. The idea is the same mentality of 
__toString(), but, for arrays.

I see possibilities for it, and on a slightly wider approach, I do think it would be nice if PHP could eventually have full operator overloading.

It goes against my better judgement for enforcing return types, but maybe a generic __cast function taking a single argument of the desired type might be an option.

The engine could enforce the return type being the same as the argument type, and the main IDE tools in use support metadata patterns to perform static analysis.

Question is, would it be either a supports/cast function pair, an exception thrower, or something else...

class X {
   /* ... */

   public function __cast($type) {
      if ($type === 'array') {
         return (array)$this;
      }

      if ($type === MyObject::class) {
         return new MyObject($this->x, $this->y);
      }

      throw new InvalidCastError($type);
   }

   public function __castable(): array {
      return [ 'array', MyObject::class ];
   }
}

Eh, my suggestion is probably a terrible ideal.

--
Mark Randall

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

Reply via email to