On 17 August 2024 01:47:20 BST, John Coggeshall <j...@coggeshall.org> wrote:
> What's the point of a Stringable interface if we can't actually implement
> __toString() for it?
Just to show the range of viewpoints on this, I'd like to mention my opinion
that Stringable is a horrible feature, with an implementation that's completely
inconsistent with the rest of the language, and no clear semantic purpose. If
your contract is "the input must be usable as a string", then the obvious type
to require is "string".
I'm not saying my opinion is objectively right, or even held by a majority, I
just wanted to provide a counterbalance of sorts.
>function fooThatWantsString(string|Stringable|UnitEnum $bar)
>{
>if(($bar instanceof UnitEnum) && !is_string($bar->value)) {
>throw InvalidArgumentException('This is exactly the sort of thing we are
>trying to get rid of with type hinting');
>} else {
>$bar = $bar->value;
>}
>
>$bar = (string)$bar;
>}
I would have thought the more common use case would be the opposite: you want
the function to be limited to a particular enum, but allow strings for backward
compatibility, and have this:
function fooThatTakesAnOption(FooOptionEnum|string $opt) {
if ( is_string($opt) ) {
$opt = FooOptionEnum::from($opt);
}
...
}
You might later want to use $opt->value, or $opt->getApiRepresentation(), or
whatever else; but at that point you know you have an object of a particular
type.
Regards,
Rowan Tommins
[IMSoP]