Re: [RFC] Adding a "Stringable" interface to PHP 8
| From: | Nicolas Grekas | Date: | Mon, 27 Jan 2020 09:29:49 +0000 |
| Subject: | Re: [RFC] Adding a "Stringable" interface to PHP 8 | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-108260@lists.php.net to get a copy of this message | ||
Le lun. 27 janv. 2020 à 10:19, Nikita Popov <nikita.ppv@gmail.com> a écrit :
> On Wed, Jan 22, 2020 at 4:47 PM Nicolas Grekas <
> nicolas.grekas+php@gmail.com> wrote:
>
>> Hello everyone,
>>
>> as announced last week, I'm officially opening a discussion for adding a
>> "Stringable" interface to PHP 8.
>>
>> The RFC and its rationale are presented here as required:
>> https://wiki.php.net/rfc/stringable
>>
>> The patch is found on GitHub, where some discussions happened already, you
>> might be interested in having a look:
>> https://github.com/php/php-src/pull/5083
>>
>> TL;DR, I think we need an interface to allow passing objects with a
>> __toString() method in a type-safe way, using the string|Stringable type..
>> Here is the stub of the proposal:
>> interface Stringable { public function __toString(): string; }
>>
>> I invite everyone to review the RFC before commenting here as I tried to
>> sum up considerations that some already had before and that you might have
>> too.
>>
>> Cheers,
>> Nicolas
>>
>
> I'm wondering whether it could make sense to automatically implement this
> interface for all classes that define __toString(). Explicitly implementing
> the interface is useful for the transition period (where old PHP versions
> also need to be supported), but when considering only PHP 8 support, I
> think it may make sense to implicitly implement the interface. If the
> __toString() functionality also works fine without implementing the
> interface, and there's probably only going to be relatively few consumers
> of the Stringable type, it will likely be quite common that the interface
> will not get implemented...
>
> Automatically implementing interfaces based on implemented methods could
> also be a general language feature (see Go interfaces for example), but
> likely not one we're interested in having in it's full generality. In this
> particular case, it seems useful though.
>
This looks like a nice improvement to the proposal, it'd be OK on my side.
For the implementation, I might need your help to implement this logic,
especially for extensions, since I suppose we'd like them to also have this
behavior of implicitly declaring the return-type + interface when they
declare the method. Could you please help me achieve that?
Nicolas