On 4/14/2016 9:25 PM, Fleshgrinder wrote: > On 4/14/2016 8:59 PM, Stanislav Malyshev wrote: >> Hi! >> >>> I don't know what is complicated about "string|Stringable" or "Foo|Bar" >>> since it is super self-explanatory. However, I find myself checking the >> >> It may be self-explanatory for you. It's much less self-explanatory for >> somebody just starting to learn. It is also very dangerous - if it's >> either Foo or Bar, can you call Foo::stuff on it or not? If it's string >> or not string, can you call strlen on it? Etc., etc. It adds a lot of >> cognitive load and complicates the whole picture. You may have a >> specific use case where it is useful (which we have yet to see btw) but >> please remember it's a language with literally millions of use cases and >> users. >> > > Reduce assertions*, enhance self-documentation, making code more robust, > perform checks in the VM and not in userland, ... > > function fn($arg) { > assert('is_string($arg) || method_exists($arg, "__toString")'); > } > > interface Stringable { > function __toString(): string; > } > > function fn(string|Stringable $arg) { > // :) > } > > You can find more information on the topic here: > > https://en.wikipedia.org/wiki/Tagged_union > > * Assertions in PHP are very error prone if combined with refactoring > due to the fact that one should enclose the actual assertion in a string. >
Oh oh oh, I forgot the very important unions *int|string* and *float|string* for overflows as one can encounter them from time to time; even in native code. -- Richard "Fleshgrinder" Fussenegger
signature.asc
Description: OpenPGP digital signature