Re: [RFC] Scalar Type Hints v0.2

From: Date: Fri, 16 Jan 2015 15:58:58 +0000
Subject: Re: [RFC] Scalar Type Hints v0.2
References: 1 2 3 4 5 6 7 8 9 10 11 12 13 14  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
Andrey Andreev wrote on 16/01/2015 15:37:
With no attempt to argue, I just thought of another example, inspired by the ones given in the RFC - it is fairly common for functions dealing with times to only accept a UNIX timestamp or otherwise just a single kind of a time unit, such as only a count of minutes or days. So where '7 years' is passed and and accepted when using a weak hint (by truncating the trailing non-numeric characters), a strict hint on the other hand may prevent the input of incorrect data (given that it's not years that are expected, of course).
That's a nice example of the advantage, actually, thank you. However, it makes me think of another approach to the whole situation, which is to make more use of Value Objects (now that the implementation of objects is no longer a huge performance hog). Obviously, for a timestamp, there is the built-in DateTimeInterface, but even if there weren't, it would be trivial to create something which existed only for type-checking a kind of sub-classed integer: class UnixTimestamp { private $value; public function get_value() { return $this->value } public function __construct($new_value) { /* validate input */ } } Obviously, the validation would still need to be written, but it would be tucked away in the shared class, rather than pasted as boilerplate at the top of every function. In many situations, the type of the argument isn't really "int" or "string", it's "mode" (from an enum or bitmask), or "text label" (maybe needs translation support) etc. So a library that really wants to document its type system should be providing wrappers for all these value types, at which point it can type hint them all by class or interface anyway. Scalar type hinting falls into the in-between category of "I want my code to be type-safe, but using a very flat type system which makes only loose guarantees about the data". Regards, -- Rowan Collins [IMSoP]

Thread (148 messages)

« previous php.internals (#80646) next »