François Laupretre wrote on 18/02/2015 18:05:
De : Rowan Collins [mailto:rowan.coll...@gmail.com]
What if we defined the types as names in the \PHP namespace, but defined
a slightly different algorithm for resolving typehints vs other uses:
function foo(\PHP\types\numeric $a) // unambiguous but unwieldy
function foo(\My\Namespace\numeric $a) // unambiguously *not* a built-in
type
function foo(numeric $a) // ambiguous, resolved at compile time
The name would be resolved as follows:
Given a typehint $type:
1) If $type begins with '\PHP\types\', interpret it it as an internal type.
2) ElseIf $type contains '\', interpret it as a class name, and proceed
with normal class resolution at runtime.
3) ElseIf \PHP\types\$type is the name of a built-in type, interpret it
as that internal type.
4) Else, interpret it as a class name, and proceed with normal class
resolution at runtime.
Basically, this means you can do the following:
class String {}
function accept_scalar_string(string $string) { ... }
function accept_string_object(\String $string) { ... }
The nice thing about this is that if we ever allow users to define
"basic" types - copy-on-write structs, range types, enums, etc - they
could "extend" these built-in types.
Does that make sense to anyone, or am I over-complicating things?
Well, that's a solution, at least theoretically speaking.
Frankly, I find it unreadable and I don't see reserving \PHP\types as a clean
solution. IMO, adding semi-virtual namespaces would be mostly confusing and
would just hide the initial name clash issue.
There are a lot of other ways to extend type hinting to user-defined types.
Maybe we will reserve namespaces for this case. In your design, where would
these user types go ? in \PHP\usertype\ ? or would they share \PHP\types with
built-in types (which recreates the same issue) ?
They'd use whatever (non-reserved) namespace the implementer wanted. e.g.
namespace Symfony\Component\TypeChecking;
basicType nonNegativeInt extends PHP\types\int {
public function isValid(int $value) {
return $value >= 0;
}
}
basicType PositiveInt extends nonNegativeInt {
public function isValid(nonNegativeInt $value) {
return $value != 0;
}
}
Obviously the format of the actual definition is made up off the top of
my head, but it shows how the namespacing would work. There's no need to
reserve a namespace for the user-defined types, because it's no worse a
burden to say "you can't name both a type and a class Foo\Bar" than to
say "you can't name two different classes Foo\Bar".
Regards,
--
Rowan Collins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php