Newsgroups: php.internals
Path: news.php.net
Xref: news.php.net php.internals:105595
Return-Path: <markyr@gmail.com>
Delivered-To: mailing list internals@lists.php.net
Received: (qmail 71201 invoked from network); 4 May 2019 21:09:23 -0000
Received: from unknown (HELO localhost.localdomain) (76.75.200.58)
  by pb1.pair.com with SMTP; 4 May 2019 21:09:23 -0000
To: internals@lists.php.net
References: <FB70FDD7-53AA-4DB4-B747-6E109BE52C2E@gmail.com>
Date: Sat, 4 May 2019 19:12:35 +0100
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:60.0) Gecko/20100101
 Thunderbird/60.6.1
MIME-Version: 1.0
In-Reply-To: <FB70FDD7-53AA-4DB4-B747-6E109BE52C2E@gmail.com>
Content-Type: text/plain; charset=windows-1252; format=flowed
Content-Language: en-GB
Content-Transfer-Encoding: 7bit
X-Posted-By: 94.1.167.52
Subject: Re: Proposal for a RFC
From: markyr@gmail.com (Mark Randall)
Message-ID: <php.internals-105595@news.php.net>

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