rfc:scalar-pseudo-type
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
rfc:scalar-pseudo-type [2017/12/24 15:20] – created fleshgrinder | rfc:scalar-pseudo-type [2017/12/24 23:33] (current) – Added object to the analogous list of other types fleshgrinder | ||
---|---|---|---|
Line 10: | Line 10: | ||
===== Proposal ===== | ===== Proposal ===== | ||
- | This RFC proposes a new '' | + | This RFC proposes a new '' |
'' | '' | ||
Line 81: | Line 81: | ||
The function [[https:// | The function [[https:// | ||
+ | |||
+ | ====== Weak Mode ====== | ||
+ | Objects with a magic '' | ||
+ | |||
+ | ====== Examples ====== | ||
+ | ======= Scalar Parameters ======= | ||
+ | PHP core already contains a multitude of procedures that could be constrained to '' | ||
+ | |||
+ | <code php> | ||
+ | function strpos(string $haystack, scalar $needle, //... | ||
+ | function printf(string $format, scalar ...$args): string {} | ||
+ | // ... and many, many, many more ... | ||
+ | </ | ||
+ | |||
+ | However, it is also useful in userland. | ||
+ | |||
+ | <code php> | ||
+ | interface Parser { | ||
+ | /** @return static */ | ||
+ | function parse(scalar $input); | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | namespace Userland\Database\MySQL; | ||
+ | |||
+ | class ReadConnection { | ||
+ | private $mysqli; | ||
+ | |||
+ | function fetch(string $query, ?scalar ...$args): ResultSet { | ||
+ | $types = ''; | ||
+ | | ||
+ | foreach ($args as $arg) { | ||
+ | if (is_float($arg)) { | ||
+ | $types .= ' | ||
+ | } elseif (is_bool($arg) || is_int($arg)) { | ||
+ | $types .= ' | ||
+ | } else { | ||
+ | $types .= ' | ||
+ | } | ||
+ | } | ||
+ | |||
+ | //... | ||
+ | $stmt-> | ||
+ | //... | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | In other words, it allows one to implement type safe method overloading over a well-defined set of types. It does not cover all possibilities just one common one. (Covering all possibilities is not possible anyways and would require union types.) | ||
+ | |||
+ | ======= Scalar Returns ======= | ||
+ | The return type constraint is less commonly useful than the one for parameters, however, it is specifically of interest while designing supertypes for others and to work around the magic '' | ||
+ | |||
+ | <code php> | ||
+ | interface Convertible { | ||
+ | function into(): scalar; | ||
+ | } | ||
+ | |||
+ | final class Longitude implements Convertible { | ||
+ | /** @var float */ | ||
+ | private $deg; | ||
+ | | ||
+ | //... | ||
+ | | ||
+ | function into(): float { | ||
+ | return $this-> | ||
+ | } | ||
+ | } | ||
+ | |||
+ | // In combination with our previous DB example. | ||
+ | $db-> | ||
+ | </ | ||
===== Backward Incompatible Changes ===== | ===== Backward Incompatible Changes ===== |
rfc/scalar-pseudo-type.1514128815.txt.gz · Last modified: 2017/12/24 15:20 by fleshgrinder