Re: String enums & __toString()

From: Date: Sat, 17 Aug 2024 12:12:40 +0000
Subject: Re: String enums & __toString()
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-125026@lists.php.net to get a copy of this message
On 17 August 2024 01:47:20 BST, John Coggeshall <john@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]

« previous php.internals (#125026) next »