On Wed, Sep 4, 2019, at 2:21 AM, Lynn wrote: > Hi, > > Would this warrant a having mixed types? By making every variable of type > "mixed" when no type is defined, regardless of what value it receives or is > initialized with, this would make an opt-in system. This behavior would > cater developers who prefer only strict types, only dynamic types, and > those that want to type their code bit by bit without putting declares that > affect whole files. > > ``` > $foo = 'foo'; > // same as > mixed $oneHundred = 100; > // difference being: > // $foo is accepted when 'string' is typed in the signature > // $oneHundred is accepted when 'int' is typed in the signature > > // no longer mixed, only accepts their defined type as value > // and is accepted only as their defined type in signatures > string $foo = 'foo'; > int $oneHundred = 100;
Yes, an implicit "mixed" type would be the only way it could be done, just like object properties that are not explicitly typed are implicitly "mixed". Whether there is a "mixed" type for explicit declaration is an open question; if it were added, it would IMO make sense to add for properties and parameters/returns, as well, for consistency. Whether or not that's wise in general I don't know. > // does imply we might need custom type definitions in the future to not > have to work with mixed > typedef Stringable = string | MyToStringInterface; > Stringable $foo = (bool) rand(0, 1) ? 'foo' : new MyStringableObject('foo'); > ``` There's a long list of reasons we want that functionality even before we get to variable types. :-) IIRC, it falls into the popular category of "this would be really useful but is harder than it sounds for complex implementation reasons, and a few people feel it's too much ceremony for a loose language." There's a number of features stuck in that bucket. > Note that this behavior would require making some decisions whether or not > in the future this opt-in behavior should change when a default value is > given, such as with C# and type inference when declaring a variable, based > on its assigned value. I could see arguments either way, but BC would probably dictate that types are not set implicitly. Otherwise, this currently valid code would break: $things = 'foo'; ... $things = ['foo', 'bar']; if (is_array($things)) { ... } else { ... } (Whether or not that's good practice is beside the point; there's ample code like that out there and breaking it when we don't have to is a no-no.) --Larry Garfield -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php