Re: Re: Improving PHP's type system

From: Date: Thu, 21 Apr 2016 19:19:35 +0000
Subject: Re: Re: Improving PHP's type system
References: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  Groups: php.internals 
Request: Send a blank email to internals+get-92604@lists.php.net to get a copy of this message
On 4/20/2016 10:18 PM, Dominic Grostate wrote: > Just a thought that crossed my mind which might satisfy both worlds. Has > anyone every considered unions as a type declaration? > > namespace Vector/TypeDefs > > union Stringable > { > as string; > as int; > as float; > > private $value; > > public function __make($type) > { > switch (type) { > case 'string': return (string) $this->value; > case 'int': return (int) $this->value; > case 'float': return (float) $this->value; > } > } > } > > my_echo_func("123"); // << A scalar variable on the outside. > > function my_echo_func(Stringable $stringable) // << a union on the inside > { > var_dump($stringable as string); // string(3) "123" > var_dump($stringable as int); // int(123) > var_dump($stringable as float); // float(123.0) > } > > Perhaps not exactly like this, but adding unions as type of class > declaration should save a hell of a lot of keywords, and may save a number > of "instanceof" type checks as well. > I do not like the idea because these types directly become part of your public API and you end up including a dozen packages just to get the basic union types in. More IO, more cache utilization, more dependencies, ... Also, one cannot change any type that was ever declared without a direct BC. No, sorry, I thing that this is very bad. :( However, the idea to make objects castable to more of the various scalar types is not new and would be awesome. interface Object { function __toBool(): bool; function __toFloat(): float; function __toInt(): int; function __toString(): string; function __toArray(): array; function __toObject(): object; function __toResource(): resource; } Auto-conversion only if not ambiguous ($o1 + $o2 where both have __toInt() and __toFloat() throws an ?Error but `(float)$o1 + (float)$o2 works so does intdiv($o1, $o2)`), next is operator overloading. ;) -- Richard "Fleshgrinder" Fussenegger

Attachment: [application/pgp-signature] OpenPGP digital signature signature.asc
« previous php.internals (#92604) next »